I'm having a hard time passing a filename to my R script. The file is a csv file with the batch parameters for multiple runs of the script. I am trying to include it here so that the user does not need to edit the R script in order to specify the location of that file.
My Windows command line syntax is:
R CMD BATCH --slave "--args fn=batch.csv" myscript.r output.txt
The closest I have gotten to retrieving this in my R script is by doing:
eval(parse(file=commandArgs()[8])))
batch_args = read.table(fn, sep=",")
I have experimented with commandArgs(trailingOnly=TRUE)
and parse(text=commandArgs()[8])
, etc., with no luck. Most of the documentation that I have seen does not apply specifically to passing filenames. Can anyone think of a solution?
What do you mean by 'no luck'? The filename is in there, in the commandArgs() function, you just have to work out how to get it out. Code and error messages are handy.
That's not a problem if the only extra argument is a filename, you know its position. What will confuse you is when you start having more complex argument passing.
You're also complicating things with passing 'fn=foo.csv'. Just pass the filename and assign it to fn in your script. If you really want to use eval you probably need to quote your filename, thus myscript.r is:
and run thus:
Where batch.csv is a simple csv file.
You could do a loop over "ca" in your script and eval everything. It's slightly dangerous though, since you could easily break basic functionality.
Personally I'd loop over ca, look for name=value pairs for a known set of names, and set them. Basically implementing getopt, but someone has probably done that already...
try
As I said in my comment, I would use
Rscript
instead ofR CMD BATCH
:where myscript.R contains:
Besides using Rscript (as Josh said) you should also use the CRAN packages getopt or optparse as they were written for this very purpose.