Search code examples
rr-markdownrscriptoptparse

How to pass an optparse argument to a R-markdown file while rendering?


I have an Report.Rmd file, that generates a pdf. Inside the .Rmd file I have some code with optparse, that receives a parameter from Rscript to use:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(optparse)
# get user as option 
option_list <- list(
  make_option(
  c("-u", "--u"), 
  type = "character", 
  default = "username"))
# parse accountId
parser <- OptionParser(
  usage = "%prog [options] file",
  option_list = option_list,
  add_help_option = F)
args <- parse_args(parser, positional_arguments = TRUE)
opt <- args$options
```

When I put this code (minus the ``` and knitr) in file.R and run it with Rscript like this:

Rscript file.R -u abcd

The code excecutes with abcd as value of the variable opt$u.

The problem is, I need to create a pdf from commandline and use the optparse argument. I can generate the pdf this with:

Rscript -e "rmarkdown::render('Report.Rmd')

Which works fine, just not with the right value for opt$u. So, how to add the -u argument to the Rscript? I tried things like Rscript -e "-u abcd;rmarkdown::render('Report.Rmd'), that gives me ERROR: option '-e' requires a non-empty argument. Rscript -e "-u abcd" -e "markdown::render('Rapportage.Rmd')" gives me the same error. How to fix this...?

EDIT: a workaround might be to call file.R, write the username to .RData, and load .RData in the .Rmd. But I hope there is an easier, cleaner way...


Solution

  • So as the OP and me figured out together, one can pass arguments in the rendering process using the params argument of rmarkdown::render(). It takes a list of named parameters. In order for it to work, you have to set up the same parameters in your YAML header.

    Example:

    This is our document file.Rmd:

    ---
    title: "MWE"
    output: pdf_document
    params:
      myName: ""
    ---
    
    ```{r color, results='markup'}
    print(params$myName)
    ```
    

    Now we can pass a value for our myName parameter using

    rmarkdown::render("file.Rmd", params = list(myName = "Martin"))
    

    Notice that when you render in the console, that you have to escape quotes inside the R command you execute:

    Rscript -e "rmarkdown::render(\"file.Rmd\", params = list(myName = \"abcd\"))"