将参数从命令行传递到 R markdown 文档

Pass Parameters from Command line into R markdown document

我是 运行 来自命令行的降价报告:

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

这个报告是在 R studio 中完成的,顶部看起来像

---
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)
```

我想要的是能够将标题和文件路径一起传递到 shell 命令中,以便它为我生成原始报告,结果是不同的 filename.html。

谢谢!

几种方法。

您可以在 YAML 中使用反引号-R 块并在执行渲染之前指定变量:

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

foo bar.

然后:

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

或者直接在RMD中使用commandArgs(),在--args:

之后填入
---
title: "`r commandArgs(trailingOnly=T)[1]`"
author: "`r commandArgs(trailingOnly=T)[2]`"
date: "July 14, 2015"
---

foo bar.

然后:

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

在这里,如果您使用命名参数 R -e ... --args --name='the title',您的 commandArgs(trailingOnly=T)[1] 就是字符串“--name=foo”——这不是很聪明。

无论哪种情况,我猜您都需要某种错误 checking/default 检查。我通常制作一个编译脚本,例如

# 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')

然后 运行 R compile.r --args ... 以我编写的脚本要处理的任何格式提供参数。