Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameters from Command line into R markdown document

Tags:

r

r-markdown

I'm running a markdown report from command line via:

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

This report was done in R studio and the top 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)
```

What I want is to be able to pass in the title along with a file path into the shell command so that it generates me the raw report and the result is a different filename.html.

Thanks!

like image 361
user1357015 Avatar asked Jul 16 '15 19:07

user1357015


1 Answers

A few ways to do it.

You can use the backtick-R chunk in your YAML and specify the variables before executing render:

---
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 the RMD and feed them in 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 do named args R -e ... --args --name='the title', your commandArgs(trailingOnly=T)[1] is the string "--name=foo" - it's not very smart.

In either case I guess you would want some sort of error checking/default checking. I usually make a compile-script, e.g.

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

And then run R compile.r --args ... supplying the arguments in whichever format I've written my script to handle.

like image 54
mathematical.coffee Avatar answered Sep 25 '22 23:09

mathematical.coffee