What is the difference between knitr ```{} chunks and <<>> chunks?

試著忘記壹切 提交于 2019-12-11 06:19:52

问题


I have seen both angled brackets:

<<>>= 
...
@

and back ticks:

```{}
...
```

used to indicate 'chunks' in the knitr documentation. What is the difference between these two?

For example, can I replace the following block of code from the documentation:

<<my-label, eval=TRUE, dev='png'>>=
set.seed(1213)  # for reproducibility
x = cumsum(rnorm(100))
mean(x)  # mean of x
plot(x, type = 'l')  # Brownian motion
@

with:

```{r my-label}
set.seed(1213)  # for reproducibility
x = cumsum(rnorm(100))
mean(x)  # mean of x
plot(x, type = 'l')  # Brownian motion
```

回答1:


The backtick syntax is used in Rmarkdown documents (Markdown mixed with R code: usually stored as file extension .rmd), while the angle-bracket syntax is used in documents that mix LaTeX with R code (usually stored as .Rnw). I'm not sure what to call the latter; they used to be "Sweave documents", but the Sweave package has been largely superseded by the knitr package. However, knitr (and the rmarkdown package) can both process both markdown+R and LaTeX+R documents ...

Your suggested substitution of

```{r chunklabel,..options..}
...
```

for

<<chunklabel,..options..>>=
...
@

seems reasonable (and very easy to just try it out!) Of course, you will need to make sure that the knitr/rmarkdown tools you're using know what syntax type you're starting with. knitr::knit seems (based on docs) to guess from the file extension. The docs for rmarkdown::render only talk about .rmd.

The easiest way to figure all this out is probably just to do a few experiments.




回答2:


One difference seems to be when using chunk references to reuse chunks, addressed by this question and the link to the documentation on Reference/Macro, which only makes use of <<>> type chunks. Duplicating the example:

<<chunk1>>=
1 + 1
@

<<chunk2>>=
<<chunk1>>
@

such that the second chunk simply duplicates the code in chunk1.

To convert this into back tick chunks, you seem to need to do:

```{r chunk1}
1 + 1
```

that is, a direct replacement as suggested in my question and Ben Bolker's answer. However, to refer to chunk 1, it seems that angled brackets are still required:

```{r chunk2}```
<<chunk1>>
```

In addition, note that leaving the code as is:

<<chunk2>>=
<<chunk1>>
@

does not work, at least with respect to rmarkdown::render with the file saved with .Rmd extension.



来源:https://stackoverflow.com/questions/41093706/what-is-the-difference-between-knitr-chunks-and-chunks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!