Passing parameters from the command line to an R markdown document

I run the markdown report from the command line through:

R -e "rmarkdown::render('ReportUSV1.Rmd')"

This report was done in studio R, and the upper part looks like

 --- title: "My Title" author: "My Name" date: "July 14, 2015" output: html_document: css: ./css/customStyles.css --- ```{r, echo=FALSE, message=FALSE} load(path\to\my\data) ``` 

I want to be able to pass in the name along with the file the path to the shell command so that it generates a raw report for me, and the result is another .html filename.

Thanks!

+5
source share
1 answer

Several ways to do this.

You can use the backtick-R piece in your YAML and specify the variables before rendering:

 --- title: "`r thetitle`" author: "`r theauthor`" date: "July 14, 2015" --- foo bar. 

Then:

 R -e "thetitle='My title'; theauthor='me'; rmarkdown::render('test.rmd')" 

Or you can use commandArgs() directly in RMD and feed them after --args :

 --- title: "`r commandArgs(trailingOnly=T)[1]`" author: "`r commandArgs(trailingOnly=T)[2]`" date: "July 14, 2015" --- foo bar. 

Then:

  R -e "rmarkdown::render('test.rmd')" --args "thetitle" "me" 

Here, if you called args R -e ... --args --name='the title' , your commandArgs(trailingOnly=T)[1] is the string "--name = foo" - it is not very smart.

In any case, I think you will want to check some kind of error / check by default. I usually do a compilation of a script, for example.

 # compile.r args <- commandArgs(trailingOnly=T) # do some sort of processing/error checking # eg you could investigate the optparse/getopt packages which # allow for much more sophisticated arguments eg named ones. thetitle <- ... theauthor <- ... rmarkdown::render('test.rmd') 

And then run R compile.r --args ... , supplying the arguments in the format in which I wrote my script for processing.

+9
source

All Articles