Is there any convenient way to automatically parse command line arguments passed to R scripts?
Something like perl's Getopt::Long
?
Is there any convenient way to automatically parse command line arguments passed to R scripts?
Something like perl's Getopt::Long
?
There are three packages on CRAN:
argparse
and json
(or simplejson
) modules.Update:
The simplest way is to use commandArgs(). Example - save the code below as "options.R":
options <- commandArgs(trailingOnly = TRUE)
options
Run using "Rscript options.R x y z". Result:
[1] "x" "y" "z"
i.e. a list of 3 elements, one per argument.
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.
May I introduce ArgumentParser
in Xmisc package? It is a command line parser inspired by Python's argparse
but it is Python-free.
http://cran.r-project.org/web/packages/Xmisc/vignettes/Xmisc-ArgumentParser.pdf
The getopt long is in the --parameter=argument
format like so
rscript script.R --parameter1=argument1 --parameter2=argument2
It can be parsed by just using basic string packages.
cli.r
library(pracma)
library(stringr)
run.arguments <- commandArgs(TRUE)
valid.run.parameters <- c( "universe", "character", "ability" )
for ( i in 1:length( run.arguments ) ) {
if ( strcmpi( substr( run.arguments[i], 1, 2 ), "--" ) & grepl( "=", run.arguments[i], fixed = TRUE) ) {
key.pair <- str_split( run.arguments[i], "=", simplify=TRUE )
run.parameter <- gsub( "--", "", key.pair[1] )
run.argument <- key.pair[2]
if ( run.parameter %in% valid.run.parameters ) {
# DO YOUR MAGIC HERE! Here is an example...
cat( run.parameter, "\n" )
cat( run.argument, "\n\n" )
}
}
}
The above script was written for brevity. See the more compelling version.
rscript cli.R --universe=MCU --character="Wade Wilson"
Output
universe
MCU
character
Wade Wilson