14.7 Use knitr::knit_expand()
to generate Rmd source
The function knitr::knit_expand()
“expands” an expression in {{ }}
(by default) to its value, e.g.,
knitr::knit_expand(text = "The value of `pi` is {{pi}}.")
## [1] "The value of `pi` is 3.14159265358979."
knitr::knit_expand(
text = "The value of `a` is {{a}}, so `a + 1` is {{a+1}}.",
a = round(rnorm(1), 4)
)
## [1] "The value of `a` is -1.1142, so `a + 1` is -0.1142."
This means that if you have an Rmd document that contains some dynamic parts in {{ }}
, you may apply knit_expand()
on the document, and then call knit()
to compile it. For example, here is a template document named template.Rmd
:
# Regression on {{i}}
```{r lm-{{i}}}
lm(mpg ~ {{i}}, data = mtcars)
```
We can build linear regression models using mpg
against all other variables one by one in the mtcars
dataset:
```{r, echo=FALSE, results='asis'}
src = lapply(setdiff(names(mtcars), 'mpg'), function(i) {
knitr::knit_expand('template.Rmd')
})
res = knitr::knit_child(text = unlist(src), quiet = TRUE)
cat(res, sep = '\n')
```
If you find it difficult to understand this example, please see Section 11.11 for the meaning of the chunk option results = 'asis'
, and Section 16.4 for the usage of knitr::knit_child()
.
当前内容版权归 Chapman & Hall/CRC 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Chapman & Hall/CRC .