Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rmarkdown: manipulate chunk options programmatically?

Is it possible to take an rmarkdown file, programmatically manipulate chunk options, and then knit based on the modified document?

I have some rmarkdown files that I want to purl, with all code (even ones with eval=FALSE) included.

At this point, my best guess is that I could (1) use sed to switch eval=FALSE to eval=TRUE, and then (2) purl. But I'd love if there's something nicer, for example maybe like:

parsed_rmd <- knitr::parse_rmd('my_rmarkdown.rmd')
for (chunk in parsed_rmd) {
 chunk$eval <- TRUE
}
knitr::purl(parsed_rmd, output = 'my_rmarkdown_as_r.R'
like image 670
DavidC Avatar asked Mar 16 '16 13:03

DavidC


1 Answers

You can set the 'eval' chunk option to a logical condition based on a parameter.

Create an Rmarkdown (.Rmd) file and define the parameter in the YAML header:

params:
     eval_optional: no

Set the 'eval' option for the code chunk you may not want to show to test the value of this parameter:

```{r optional_code, eval= (params$eval_optional == "Yes")}
# chunk with code you only want to show sometimes
```

Then call rmarkdown_render with the appropriate parameter:

rmarkdown::render(file = "myreport.rmd", params = list(eval_optional = "yes")

See http://rmarkdown.rstudio.com/developer_parameterized_reports.html for more on using parameters

like image 172
DonJ Avatar answered Sep 30 '22 16:09

DonJ