Holger Hoefling
Holger Hoefling

Reputation: 438

Tangle knitr code blocks into not one but several files

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?

Upvotes: 9

Views: 269

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121157

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
```

Upvotes: 3

Related Questions