Is there any convenient way to automatically parse command line arguments passed to R scripts?
Something like perl's Getopt::Long
?
Use the commandArgs() Function to Retrieve Arguments in R Arguments passed on the command line should be retrieved using the commandArgs() function. We will use it with the argument trailingOnly=TRUE . The function returns a character vector.
Argument Parsing using sys.Your program will accept an arbitrary number of arguments passed from the command-line (or terminal) while getting executed. The program will print out the arguments that were passed and the total number of arguments.
Getopt is not used for parsing command-line arguments automatically.
argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With