Pass Parameters from Command line into R markdown

2019-02-12 20:56发布

问题:

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!

回答1:

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.



标签: r r-markdown