Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional `echo` (or eval or include) in rmarkdown chunks

Tags:

I would like to create an Rmarkdown document (pdf or html) that has some chunks "executed" conditionally. The particular case I have in mind is that I might want a more verbose and documented version of the output for internal review by colleagues, and a shorter version for external consumers. I may not want or need to show data manipulation steps to a client, but just key graphs and tables. I also do not want to make two separate documents or have to manually indicate what to show or not.

Is there a way to set a switch at the beginning of the Rmd that indicates, e.g., verbose=T that will run all chunks or verbose=F that toggles echo=F (or include=F)?

Thank you.

like image 303
CJGodfrey Avatar asked Aug 18 '14 00:08

CJGodfrey


1 Answers

knitr options can be stated as R expressions. Per the "output" documentation on the knitr webpage:

Note all options in knitr can take values from R expressions, which brings the feature of conditional evaluation introduced in the main manual. In short, eval=dothis means the real value of eval is taken from a variable named dothis in the global environment; by manipulating this variable, we can turn on/off the evaluation of a batch of chunks.

In other words if you write some chunks like:

```{r label} doNextChunk <- as.logical(rbinom(1,1,.5)) ```  ```{r conditional, eval = doNextChunk} "hello world!" ``` 
like image 151
Thomas Avatar answered Oct 24 '22 09:10

Thomas