Pass Parameters from Command line into R markdown document

与世无争的帅哥 提交于 2019-12-18 12:28:12

问题


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.



来源:https://stackoverflow.com/questions/31463143/pass-parameters-from-command-line-into-r-markdown-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!