Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tangle knitr code blocks into not one but several files

Tags:

r

knitr

I am a new user to knitr. I know that knitr can "tangle out" (taken from the Literate programming community) or extract source code blocks into an R script file. Being an org-mode-user, I am used to being able to specify a specific file for each code block, with potentially the same file for different blocks. When "tangling" or extracting source in org-mode, instead of having one output code file, several code files are produced (this helps with modularity in large projects).

I wonder if something similar is possible in knitr? Can I specify the output file in knitr on a block by block basis?

like image 838
Holger Hoefling Avatar asked Aug 05 '16 07:08

Holger Hoefling


1 Answers

There are at least two different readings of your question, each requiring slightly different workflows.

If each chunk is going to be written into a separate output document, then to assist modularity, you should split the reporting part down into multiple documents. Since knitr supports child documents, you can always recombine these into larger documents in any combinations that you like.

If you want conditional execution of some chunks, and there are a few different combinations of conditions that can be run, use an R Markdown YAML header, and include a params element.

----
params:
  report_type: "weekly" # should be "weekly" or "yearly"
----

You can set which chunks are run by setting the eval and include chunk options.

```{r, some_chunk, eval = params$report_type == "weekly", include = params$report_type == "weekly"}
# chunk contents
```
like image 100
Richie Cotton Avatar answered Oct 26 '22 00:10

Richie Cotton