R Markdown Parameters | Drew Seewald | Towards Data Science

We’ve all been in a meeting where someone asks, “can you run that analysis again for a different time period,” or, “can you run it for group B instead of group A,” or, “can you send me that analysis so that I can play around with it?”
There are some problems that we often encounter when trying to fulfill those requests. Changing the source of an analysis can be difficult, whether it is from one .csv to another or from the testing database to the production database. If the connection or file to import is defined in multiple places, it can be easy to miss one and have invalid output. We run into the same issue when switching the analysis from a group A to a group B or changing the time frame of the analysis data. It could be in multiple filters that all need to get changed.
Giving an analysis out can also be troublesome. When working on some ad hoc analysis, it is common to leave database passwords in the code while working out the details of the analysis. Giving out that R Markdown file or leaving it on a shared network drive raises security concerns. While dotenv is an option, it requires slightly more setup to work correctly.
towardsdatascience.com
Luckily R Markdown has a feature called parameters which provide solutions to all of these problems.
Parameters in an R Markdown document are very simple to use. In the yaml header (the section at the top of the markdown document), you just have to add a couple new lines for your parameters to hardcode them in. Once they’re coded in, they will be available in the params object for use in the rest of the analysis. By referencing the parameters from the yaml header, any updates to them that need to be made will only require one change.
For this example, we’ll look at the gapminder data set. This is a data set available from the gapminder package. It has a subset of the indicators collected by the Gapminder foundation. Check out Hans Rosling’s (one of the Gapminder founders) TED talk, or the Gapminder website for more information.
# Setup# install.packages("gapminder")library(gapminder)# The data framegapminder
The gapminder data set contains 6 variables: country, continent, year, lifeExp (life expectancy), pop (population), and gdpPercap (gross domestic product per capita).
We’ll start by filtering the data frame for the year 2002. Using the tidyverse, that code looks like this:
library(tidyverse)gapminder %>%    filter(year == 2002) %>%    head()
We might want to run this report for a different year, making this a good candidate to create a parameter for. In our yaml header, we will add another item called params and underneath it, with 2 spaces in front, we’ll create a year parameter. When running an R Markdown, a params object will be created, and the named parameters will be available for our use.
---title: "Hardcoded Parameters"author: "RealDrewData"date: "7/6/2021"output: html_documentparams:  year: 2002---
Now we can return to our filtering code. We’ll replace 2002 with the year parameter we just created.
library(tidyverse)gapminder %>% filter(year == params$year) %>% head()
We can also use the year parameter in other places in the code, such as a label in a plot. Let’s create a scatter plot with GDP per capita on the x axis, life expectancy on the y axis, population for the size of the points, and continent for color. In our labels, we can use the paste() function and our params$year to build a title for the plot that updates with the parameter.
gapminder %>%    filter(year == params$year) %>%    ggplot(aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) +    geom_point() +    labs(title = paste("Life Expectancy and GDP for", params$year), x = "GPD Per Capita", y = "Life Expectancy")
Markdown sections are where we have the plain text. We can run code inline to return values and have them display in the output text. For example, we may have a section header that says:
## Gapminder Analysis for 2002
This will not update when we change our parameter. To correct this, we can use inline code to grab the year from the params object. The r is there to say we are going to use R code. When knitting the document, this will be exactly the same as the previous code, assuming the year parameter is still set to 2002.
## Gapminder Analysis for 'r params$year'
Parameters don’t have to be numeric, they can also be boolean. One common example of this is to create switches to modify the behavior when the Markdown is knitting. One example is whether or not to print code in the final output. When showing something to a manager or executive, you may not want to see code, but when reviewing with the team, code can be more important.
towardsdatascience.com
For this, we’ll create another parameter under year: show_code.
---title: "Hardcoded Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams:  year: 2002  show_code: FALSE---
Usually in the setup chunk knitting options are defined. In our case, we want to set the echo option equal to show_code. Since we set this to FALSE, it will prevent our code from showing up in the final output.
knitr::opts_chunk$set(echo = params$show_code)
Hardcoding parameters in Markdown clearly adds some major benefits. What if someone who isn’t as familiar with Markdown wants to modify a report or you want to quickly rerun for a different period? Dynamic parameters can be helpful here.
With the gapminder data frame, there is some nuance in the data available. Every 5 years is in the data frame, starting at 1952 and ending in 2007. For someone who doesn’t know the data, they could easily change the parameter to 1953 and be very confused when no data shows up. To change that, we can add a custom prompt by modifying the year parameter in the yaml header.
We’ll add another sub level under year with the settings that we want. In this case we want the label to be called year, the default value to be 2002, and for the input to be a slider. We can also specify minimum and maximum values, and how many steps are between each value.
---title: "Dynamic Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams:  year:    label: "Year"    value: 2002    input: slider    min: 1952    max: 2007    step: 5    sep: ""  show_code: FALSE
To get the prompt to appear, click the arrow next to the knit button. Click on knit with parameters.
This will bring up a window with a slider labelled year. This slider will have the restrictions we set above. Sliding the slider to 1977 and clicking knit is the same as changing the value of year in the yaml header. The added benefit is that we know that the input will be the correct type and we can limit the options that can be chosen to make sure that data appears on the final output.
You’ll also notice that a check box input was created for the show_code parameter. This is the default for boolean parameters.
Again, we aren’t limited to just numeric and boolean types. If I have a call to a database where the code needs a username and password, we can create parameters for those as well.
The username can be a text field. That input is denoted by the text input. The value is the value to default to, in this case blank. placeholder is the text displayed in the text box when it is blank. For the password input, we can use the password variant of the text input. This will obfuscate the text that is typed into it, much like when you are logging into a website.
---title: "Dynamic Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams:  year:    label: "Year"    value: 2002    input: slider    min: 1952    max: 2007    step: 5    sep: ""  show_code: FALSE  username:    label: "username"    value: ""    input: text    placeholder: "username"  password:    label: "PWD"    value: ""    input: password    placeholder: "password"---
When we click knit with parameters, we now see a text box input and a password input. This is by no means best practice, but it gives you an example of what you can do with dynamic parameters.
There are many other options for inputs you can use to set your parameters. A more comprehensive list can be found in the Shiny Widget Gallery.
Parameters serve multiple purposes in R Markdown. They allow you to make a single change in a document that impacts the entire document. They make it easy to run the same report for a different period, or event a different audience. They also can aid in sharing analysis with others, but there may be better options for this particular use case.
R Markdown: The Definitive Guide, by Yihui Xie, J. J. Allaire, Garrett Grolemund. Written by members of the RStudio team, this covers everything you could ever want to know about R Markdown. It is available online for free here, but you can also purchase a hardcopy
Shiny Widget Gallery: interactive examples of all the shiny widgets that can be used to dynamically set the parameters in an R Markdown document.
Hans Rosling TED Talk: Hans Rosling is one of the founders of the Gapminder Foundation. This TED talk gives some background on the data used in the examples. It always gets me fired up and ready to do some data analysis!