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.,

  1. knitr::knit_expand(text = "The value of `pi` is {{pi}}.")
  2. ## [1] "The value of `pi` is 3.14159265358979."
  3. knitr::knit_expand(
  4. text = "The value of `a` is {{a}}, so `a + 1` is {{a+1}}.",
  5. a = round(rnorm(1), 4)
  6. )
  7. ## [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:

  1. # Regression on {{i}}
  2. ```{r lm-{{i}}}
  3. lm(mpg ~ {{i}}, data = mtcars)
  4. ```

We can build linear regression models using mpg against all other variables one by one in the mtcars dataset:

  1. ```{r, echo=FALSE, results='asis'}
  2. src = lapply(setdiff(names(mtcars), 'mpg'), function(i) {
  3. knitr::knit_expand('template.Rmd')
  4. })
  5. res = knitr::knit_child(text = unlist(src), quiet = TRUE)
  6. cat(res, sep = '\n')
  7. ```

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