Reputation: 11120
Consider the following test.Rmd
:
```{r setup, purl=FALSE}
opts_chunk$set(purl=FALSE)
opts_template$set(nopurl = list(purl=FALSE))
```
```{r test1}
print(1)
```
```{r test2, opts.label='nopurl'}
print(2)
```
```{r test3, purl=FALSE}
print(3)
```
purl('test.Rmd')
gives test.R
, where none of the test* chunks is supposed to be purled, but:
## ----test1---------------------------------------------------------------
print(1)
## ----test2, opts.label='nopurl'------------------------------------------
print(2)
Only test3
is not purled, the rest are purled, despite the global option opts_chunk$set(purl=FALSE)
and the label nopurl
.
Why?
Upvotes: 5
Views: 2185
Reputation: 11120
Based on Yihui feedback, the way to go is like follows:
```{r setup, purl=FALSE}
knit_hooks$set(purl = hook_purl)
opts_template$set(nopurl = list(purl=FALSE))
opts_template$set(dopurl = list(purl=TRUE))
```
```{r test}
print(1)
```
```{r test2, opts.label='nopurl'}
print(2)
```
```{r test3, opts.label='dopurl'}
print(3)
```
With this approach, you don't need to:
purl('test.Rmd')
You simply:
knit('test.Rmd')
and get both the usual test.md
and the test.R
file. The latter is as follows:
## ----test----------------------------------------------------------------
print(1)
## ----test3, opts.label='dopurl'------------------------------------------
print(3)
As you see, given knit_hooks$set(purl = hook_purl)
, the default behaviour for chunks is purling.
In actual use nopurl
and dopurl
will collect more options to be set together with (no-)purling.
Anyway, when considering the following note:
N.B. There is no guarantee that the R script generated by 'purl()' can reproduce the computation done in 'knit()'. The 'knit()' process can be fairly complicated (special values for chunk options, custom chunk hooks, computing engines besides R, and the 'envir' argument, etc). If you want to reproduce the computation in a report generated by 'knit()', be sure to use 'knit()', instead of merely executing the R script generated by 'purl()'. This seems to be obvious, but some people just do not get it.
it seems wise to always use knit_hooks$set(purl = hook_purl)
and set the purl=FALSE
when purl is not needed.
Upvotes: 2
Reputation: 30114
It is not a bug, but just that purl()
does not executed any code chunks, so the first code chunk was not really executed. The purl()
function is not reliable in many ways, and see ?knitr::hook_purl
instead. That said, I'd not recommend purling a document at all; knitting is more reliable (See the Note section in ?knitr::purl
).
Upvotes: 2