Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R / Sweave arguments

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.

like image 372
MadSeb Avatar asked Feb 22 '12 17:02

MadSeb


1 Answers

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.

like image 120
Yihui Xie Avatar answered Sep 18 '22 17:09

Yihui Xie