This is a short demo of how to use brew
and knitr
in combination with each other to get the best of the templating facilities in brew
and the literate programming functions in knitr
. The main idea is to write a function brew_knit
# Preprocess template using brew and then run knit on the output
brew_knit <- function(template, params, ...){
brew::brew(template, envir = list2env(params))
input = gsub(".Rnwe", '.Rnw', template)
knitr::knit(input)
}
brew_knit
first expands the template
using params
passed to it. The expanded template is then run through knit
to produce the final output. One can pass further parameters to knit
using the ...
argument. Moreover, this function can be generalized to allow different markup document formats.
Shown below is a an example taken from Prof. Frank Harrell’s mail on the knitr mailing list. The template is doc.Rnwe
which is expanded to doc.Rnw
and then knit
to doc.tex
.
UPDATE: At times, you might want to inherit the paramter list from the global environment (suggestion by @baptiste). Although undesirable IMHO from a reproducibility perspective, it can be done by tweaking the brew_knit
function
# Preprocess template using brew and then run knit on the output
brew_knit2 <- function(template, params, envir = parent.frame(), ...){
if (missing(params)){
myenvir = envir
} else {
myenvir = list2env(params)
}
brew::brew(template, envir = myenvir)
input = gsub(".Rnwe", '.Rnw', template)
knitr::knit(input)
}