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."
  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) {
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().