Skip to content
Prev 305005 / 398506 Next

[Rscript] difficulty passing named arguments from commandline

The trailling arguments to Rscript, generally read by commandArgs(TRUE), come
into R as a vector of character strings.  Your script can interpret those character
strings in many ways.  The OP's script processed them all with
   eval(parse(text=arg[i]))
so all the arguments had to be valid R expressions: strings must be quoted, unquoted
things are treated as names of R objects, slash means division, "=" and "<-" mean
assignment, etc.

If that is a problem, don't use parse() to interpret the strings; use sub() or strsplit()
to extract substrings and do what you want with them.  (This is somewhat safer
than using eval(parse(text=)) because it can do less.)

E.g.,

% R --quiet --args ./file.txt logFile=./file.log var3=1/3 'stringVar <- paste("var3 is", var3)'
[1] "./file.txt"
[2] "logFile=./file.log"
[3] "var3=1/3"
[4] "stringVar <- paste(\"var3 =\", var3)"
[1] "args"      "dataFile"  "logFile"   "stringVar" "var3"
[1] "./file.txt"
[1] "./file.log"
[1] "var3 is 0.333333333333333"
[1] 0.3333333

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com