views:

183

answers:

3

Is there any convenient way to automatically parse command line arguments passed to R scripts?

Something like perl's Getopt::Long?

+1  A: 

There are two packages on CRAN:

  • getopt: C-like getopt behavior
  • optparse: a command line parser inspired by Python's optparse libary
rcs
+2  A: 

The simplest way is to use commandArgs(). Example - save the code below as "options.R":

options <- commandArgs(trailingOnly = T)
options

Run using "Rscript options.R x y z". Result:

[1] "x" "y" "z"

i.e. a list of 3 elements, one per argument.

neilfws
A: 

Just to complement the Rscript answer:

edd@max:~$ r -e 'print(argv)' flim flam flom
[1] "flim" "flam" "flom"
edd@max:~$ 

We just use argv in littler. I had good luck with getopt, the older of the two available parsing packages.

Dirk Eddelbuettel