When I purl/tangle a document to extract the R chunks into a script, is there any way to:
- exclude an arbitrary chunk (by name say)?
- if not, exclude a chunk if
eval=F
(or perhaps I can define a chunk hook/optioninclude=F
)?
For example, suppose I have the following Rmd:
```{r setup, echo=F}
library(MASS)
```
First, we perform the setup (assume for some reason I need to evaluate `setup`
silently before I wish to display the chunk to the user, hence the repetition)
```{r setup, eval=F}
```
Here's the function I've been explaining:
```{r function}
plus <- function (a, b) a + b
```
And here's an example of its use:
```{r example}
plus(1, 2)
```
The tangled script looks like this:
## @knitr setup, echo=F
library(MASS)
## @knitr setup, eval=F
library(MASS)
## @knitr function
plus <- function (a, b) a + b
## @knitr example
plus(1, 2)
I have the idea that since I didn't want particular chunks to be evaluated, they at the very least should not appear in the output (in the example above, the second setup
chunk).
Additionally it would be nice for me to mark some chunks as "invisible" with respect to the tangled output. I don't want the example
chunk in my output script (it was nice in the Rmd for purposes of documentation, but I want to be able to tangle the Rmd and then just source('myfile.r')
if I wish to use the plus
function, without having to worry about these extra examples executing. Currently I tangle the Rmd and then manually edit out the chunks I don't want out of the script, which seems against the principle of just writing the one Rmd which will provide both documentation and script without extra effort.)
Although this is more a trick than a solution, you can still modify the script resulting from purl with some regular expressions.
For example with the following function (maybe there is a simpler solution for the regex) :
You can then do this to remove all code chunk containing eval=F :
You can do this to remove the chunk named "function" or "example" (and in fact it will remove any chunk that contains these words somewhere but this could be changed by changing the regex):
The tangle processing block doesn't currently expand params, but we can make it do so...
Then purl() exclusion can be controlled using option arguments...
Since
knitr
1.3, there is a new chunk optionpurl = TRUE/FALSE
that allows one to include/exclude certain code chunks forpurl()
.