问题描述
我正在使用 R 和 Sweave 生成报告.
R CMD Sweave MyReport.Rnw
我希望能够向 R 代码发送参数,因为报告当然是动态".所以,我希望能够执行以下操作:>
R CMD SWeave MyReport.Rnw PatientId=5
...并让 R 代码读取变量中的 PatientId
值...
我该怎么做?有人提到使用环境变量,但这似乎是一个不优雅的解决方案.
要获取从 R 命令行传递的参数,可以使用函数 commandArgs()
,但不幸的是 R CMD Sweave
不支持额外的命令行选项.但是,您仍然可以通过 R -e
调用 Sweave,例如
R -e "Sweave('MyReport.Rnw')" --args PatientId=1
在 MyReport.Rnw
中,您对 commandArgs(TRUE)
进行了一些文本处理,它为您提供了一个字符串 PatientId=1
这种情况.
但我认为更好的做法是在 R 脚本中直接使用函数Sweave()
;例如在这种情况下,您可以在像
PatientId
并且在
MyReport.Rnw
中,您可以直接使用全局变量PatientId
.如果您想生成一系列报告,您甚至可以为 PatientId
使用循环.
I'm using R and Sweave to generate a report.
I want to be able to send arguments to the R code because the report is , of course, "Dynamic".So, I would like to be able to do something like this:
...and have the R code read the
PatientId
value in a variable...
How do I do this? Somebody mentioned using environment variables but that's seems like a non-elegant solution.
解决方案
To get arguments passed from R command line, you can use the function
commandArgs()
, but unfortunately R CMD Sweave
does not support extra command line options. However, you can still call Sweave by R -e
, e.g.
R -e "Sweave('MyReport.Rnw')" --args PatientId=1
In
MyReport.Rnw
, you do some text processing on commandArgs(TRUE)
, which gives you a character string PatientId=1
in this case.
But I believe a better practice is to use the function
Sweave()
in an R script directly; e.g. in this case you can write the process in a script like
PatientId <- 1
Sweave("MyReport.Rnw")
and in
MyReport.Rnw
you use the global variable PatientId
directly. If you want to generate a series of reports, you can even use a loop for PatientId
.
这篇关于R/Sweave 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!