I have been using R CMD BATCH my_script.R
from a terminal to execute an R
script. I am now at the point where I would like to pass an argument to the command, but am having some issues getting it working. If I do R CMD BATCH my_script.R blabla
then blabla
becomes the output file, rather than being interpreted as an argument available to the R script being executed.
I have tried Rscript my_script.R blabla
which seems to pass on blabla
correctly as an argument, but then I don't get the my_script.Rout
output file that I get with R CMD BATCH
(I want the .Rout
file). While I could redirect the output of a call to Rscript
to a file name of my choosing, I would not be getting the R input commands included in the file in the way R CMD BATCH
does in the .Rout
file.
So, ideally, I'm after a way to pass arguments to an R script being executed via the R CMD BATCH
method, though would be happy with an approach using Rscript
if there is a way to make it produce a comparable .Rout
file.
My impression is that R CMD BATCH
is a bit of a relict. In any case, the more recent Rscript
executable (available on all platforms), together with commandArgs()
makes processing command line arguments pretty easy.
As an example, here is a little script -- call it "myScript.R"
:
## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))
And here is what invoking it from the command line looks like
> Rscript myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
Edit:
Not that I'd recommend it, but ... using a combination of source()
and sink()
, you could get Rscript
to produce an .Rout
file like that produced by R CMD BATCH
. One way would be to create a little R script -- call it RscriptEcho.R
-- which you call directly with Rscript. It might look like this:
## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]
sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)
To execute your actual script, you would then do:
Rscript RscriptEcho.R myScript.R 5 100
[1] 98.46435 100.04626 99.44937 98.52910 100.78853
which will execute myScript.R
with the supplied arguments and sink interleaved input, output, and messages to a uniquely named .Rout
.
Edit2:
You can run Rscript verbosely and place the verbose output in a file.
Rscript --verbose myScript.R 5 100 > myScript.Rout