17.3 Render R Markdown with rmarkdown::render()

If you do not use RStudio or any other IDE, 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 country:

for (state in state.name) {
  rmarkdown::render(
    '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()), so objects created in your code chunks will stay inside this environment, without polluting your current global environment. On the other hand, if you prefer rendering the Rmd document in a new R session so that objects in your current R session will not pollute your Rmd document, you may call rmarkdown::render in xfun::Rscript_call(), e.g.,

xfun::Rscript_call(
  rmarkdown::render,
  list(input = 'my-file.Rmd', output_format = 'pdf_document')
)

This method is similar to clicking the Knit button in RStudio, which also renders the Rmd document in a new R session. In case you need to render an Rmd document inside another Rmd document, we strongly recommend that you use this method instead of directly calling rmarkdown::render() in a code chunk, because rmarkdown::render() creates and relies on a lot of side effects internally, which may affect rendering other Rmd documents in the same R session.

The second argument of xfun::Rscript_call() takes a list of arguments to be passed to rmarkdown::render(). In fact, xfun::Rscript_call is a general-purpose function to call any R function (with arguments optionally) in a new R session. Please see its help page if you are interested.