16.2 Render R Markdown with rmarkdown::render()

If you do not use RStudio or any other IDEs, you need to know this fact: R Markdown documents are rendered through the function rmarkdown::render(). This means you can programmatically render an R Markdown document in any R script. For example, you could render a series of reports in a for-loop for each state of a coutry:

for (state in state.name) {
    'input.Rmd', output_file = paste0(state, '.html')

The output filename will be different for each state. You can also make use of the state variable in the document input.Rmd, e.g.,

title: "A report for `r state`"
output: html_document

The area of `r state` is `r state.area[state.name == state]`
square miles.

You may read the help page ?rmarkdown::render to know other possible arguments. Here we just want to mention two of them, i.e., the clean and envir arguments. The former (clean) is particularly helpful for debugging when anything goes wrong with the Pandoc conversion. If you call rmarkdown::render(..., clean = FALSE), all intermediate files will be preserved, including the intermediate .md file knitted from the .Rmd file. If Pandoc signals an error, you may start debugging from this .md file. The latter (envir) offers a way to render a document with the guarantee of an empty new environment when you call rmarkdown::render(..., envir = new.env()).