2

I'm creating an HTML output from a .R script with the command rmarkdown::render(input = "my_script.R"). It calls knitr::spin() and successfully produces an HTML output. In that .R file, there is a filtering variable school_level whose value I want to control from the call to render().

I know for an RMarkdown file I'd specify a parameter in the YAML header. But how do I do that for a .R script? I'm not seeing it in guides like the RMarkdown Cookbook.

Say the line I want to modify in my .R script is:

good_data <- my_data %>%
  filter(level == school_lvl)

What do I change in my .R script to control the value of school_lvl from the call to rmarkdown::render? Making the value of school_lvl be "Elementary" or "Secondary".

Sam Firke
  • 21,571
  • 9
  • 87
  • 105

1 Answers1

2

If you want to pass some parameters from the params argument of rmarkdown::render() function to knitr, it's a bit complicated as the knitr::spin() function overrides parameters. You can specify a commented header in your R script (as seen in the documentation), with empty parameter value, e.g. test.R:

#' ---
#' params:
#'   wanted_cyl: null
#' ---

library(tidyverse)

mtcars %>%
 filter(cyl == params$wanted_cyl)

Then you can call:

rmarkdown::render(input = "test.R", params = list("wanted_cyl" = 6))
  • 1
    This is a great minimal example, thanks. It worked in this test example and then not in my .R script, and was enough for me to isolate my underlying problem: the previous author of this script started with `rm(list = ls())` which was erasing the parameter! – Sam Firke Jun 30 '20 at 21:04