Knitr: add to the previous story in a new code snippet

I use the package knitrfor R to create a LaTeX document combining text with embedded R-graphics and output.

Usually they write something like this:

We plot y vs x in a scatter plot and add the least squares line:
<<scatterplot>>=
plot(x, y)
fit <- lm(y~x)
abline(fit)
@

which works great. (For those unfamiliar with knitror Sweave, this code outputs the code and outputs it in the verbatim environment of LaTeX, and also adds the completed graph as a figure in the LaTeX document.)

But now I would like to write a more detailed step-by-step comment, for example:

First we plot y vs x with a scatterplot:
<<scatterplot>>=
plot(x, y)
@
Then we regress y on x and add the least squares line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
@

, knitr . addline , , scatterplot, . .

knit(), , plot() ?

, LaTeX , ?

, , . , grid knitr? 2013 2016 . 2013 : , knitr ?

+4
2

knitr::opts_knit$set(global.device = TRUE), , . :

\documentclass{article}

\begin{document}
<<setup, include=FALSE>>=
knitr::opts_knit$set(global.device = TRUE)
@

First we plot y vs x with a scatterplot:
<<scatterplot>>=
x = rnorm(10); y = rnorm(10)
plot(x, y)
@
Then we regression y and x and add the least square line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
@

\end{document}
+2

, , chunk eval=FALSE. , eval=FALSE plot(x,y).

: One - , , , plot(x,y). , , , .

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r data}
set.seed(10)
x=rnorm(10)
y=rnorm(10)
```

First we plot y vs x with a scatterplot:

```{r scatterplot, eval=FALSE}
plot(x, y)
```

Then we regress y on x and add the least squares line to the plot:

```{r addline, eval=FALSE}
fit <- lm(y~x)
abline(fit)
```

```{r echo=FALSE}
plot(x,y)
fit <- lm(y~x)
abline(fit)
```

:

enter image description here

+3

Source: https://habr.com/ru/post/1690503/


All Articles