R knitr: Possible to programmatically modify chunk labels?
For anyone else who comes across this post, I wanted to point out that @Yihui has provided a formal solution to this question in knitr 1.0 with the introduction of the knit_expand()
function. It works great and has really simplified my workflow.
For example, the following will process the template script below for every level of mtcars$cyl
, each time replacing all instances of {{ncyl}}
(in the template) with its current value:
# My report
```{r}
data(mtcars)
cyl.levels <- unique(mtcars$cyl)
```
## Generate report for each level of cylinder variable
```{r, include=FALSE}
src <- lapply(cyl.levels, function(ncyl) knit_expand(file = "template.Rmd"))
```
`r knit(text = unlist(src))`
Template:
```{r, results='asis'}
cat("### {{ncyl}} cylinders")
```
```{r mpg-histogram-{{ncyl}}cyl}
hist(mtcars$mpg[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
```{r weight-histogam-{{ncyl}}cyl}
hist(mtcars$wt[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
set chunk options on basis of chunk contents
I tend to agree with @user2554330 that you may want to cache the function myFun()
instead of code chunks (e.g., with memoise).
Anyway, to answer your question: yes, it is possible to set cache = TRUE
with an option hook, e.g.,
knitr::opts_hooks$set(cache = function(options) {
if (any(grepl('myFun(', options$code))) {
options$cache <- TRUE
}
options
})
grepl()
is not an entirely robust way to check if the code chunk contains a call to myFun()
. If you want a most robust way, you may try utils::getParseData()
.
Reuse R child Rmd files - error: duplicate chunk labels
If found a solution:
load("logfile1.Rda")
z <- 1
src <- lapply(z, function(z) knitr::knit_expand(file = "child1.Rmd"))
r knitr::knit(text = unlist(src))
src <- lapply(z, function(z) knitr::knit_expand(file = "child2.Rmd"))
r knitr::knit(text = unlist(src))
load("logfile2.Rda")
z <- 1
src <- lapply(z, function(z) knitr::knit_expand(file = "child1.Rmd"))
r knitr::knit(text = unlist(src))
src <- lapply(z, function(z) knitr::knit_expand(file = "child2.Rmd"))
r knitr::knit(text = unlist(src))
Within the child-files I added {{z}}
to each chunk label.
Related Topics
What Are the Double Colons (::) in R
Inst and Extdata Folders in R Packaging
Multiple Graphs in One Canvas Using Ggplot2
Unique() for More Than One Variable
Dynamic Column Names in Data.Table
Create Dataframe from a Matrix
How to Pass Parameters to a Shiny App via Url
Issue When Importing Dataset: 'Error in Scan(...): Line 1 Did Not Have 145 Elements'
What Do the %Op% Operators in Mean? for Example "%In%"
Generate Dynamic R Markdown Blocks
How to Convert Data.Frame Column from Factor to Numeric
Linear Regression with a Known Fixed Intercept in R
How to Change 'Maximum Upload Size Exceeded' Restriction in Shiny and Save User File Inputs
Referring to Data.Table Columns by Names Saved in Variables
Removing Display of Row Names from Data Frame