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 unfortunatelyR CMD Sweave
does not support extra command line options. However, you can still call Sweave byR -e
, e.g.In
MyReport.Rnw
, you do some text processing oncommandArgs(TRUE)
, which gives you a character stringPatientId=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 likeand in
MyReport.Rnw
you use the global variablePatientId
directly. If you want to generate a series of reports, you can even use a loop forPatientId
.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: