R / Sweave arguments

2019-02-13 21:22发布

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.

2条回答
Root(大扎)
2楼-- · 2019-02-13 22:04

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.

查看更多
走好不送
3楼-- · 2019-02-13 22:08

You need to 'write' the value where it can be 'read':

  • environment variables, as mentioned, are an easy approach with sys.getenv()

  • configuration or data files you can read

  • data base storage

etc pp. Recall that R code is really executed so you can always do a two-step:

rScriptOne.r                   # write to foo.txt
R CMD Sweave MyReport.Rnw      # reads from foo.txt
查看更多
登录 后发表回答