17.4 Parameterized reports
In Section 17.3, we mentioned one way to render a series of reports in a
for-loop. In fact,
rmarkdown::render() has an argument named
params specifically designed for this task. You can parameterize your report through this argument. When you specify parameters for a report, you can use the variable
params in your report. For example, if you call:
input.Rmd, the object
params will be a list that contains the
Another way to specify parameters for a report is to use the YAML field
Note that you can include as many parameters in the
params YAML field or the
params argument of
rmarkdown::render(). If both the YAML field and the argument are present, the parameter values in the argument will override the corresponding parameters in YAML. For example, when we call
rmarkdown::render(..., params = list(state = 'Iowa', year = 2018) on the previous example that has the
params$state will become
Iowa (instead of
params$year will become
2018 (instead of
2019) in the R Markdown document.
When rendering the same R Markdown document to a series of reports, you need to adjust the
output_file argument of
rmarkdown::render(), to make sure each report has its unique filename. Otherwise, you will accidentally override certain report files. For example, you can write a function to generate a report for each state and each year:
Then you can use nested
for-loops to generate all reports:
At the end, you will get a series of report files like
For parameterized reports, you can also input parameters interactively through a graphical user interface (GUI) created from Shiny. This requires you to provide a
params field in YAML, and rmarkdown will automatically create the GUI using the appropriate input widgets for each parameter (e.g., a checkbox will be provided for a Boolean parameter).
To start the GUI, you can call
params = 'ask' if you do not use RStudio:
If you use RStudio, you can click the menu
Knit with Parameters behind the
Knit button. Figure 17.1 shows an example GUI for parameters.
Xie, Yihui, J. J. Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown.