R/Sweave 参数 [英] R / Sweave arguments

查看:25
本文介绍了R/Sweave 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 <- 1Sweave("MyReport.Rnw")

并且在MyReport.Rnw 中,您可以直接使用全局变量PatientId.如果您想生成一系列报告,您甚至可以为 PatientId 使用循环.

I'm using R and Sweave to generate a report.

R CMD Sweave MyReport.Rnw

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:

R CMD SWeave MyReport.Rnw PatientId=5

...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 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆