I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on Windows.
I can't find info on how to read parameters supplied on the command-line into my R script. I'd be surprised if it can't be done, so maybe I'm just not using the best keywords in my Google search...
Any pointers or recommendations?
In bash, you can construct a command line like the following:
You can see that the variable
$z
is substituted by bash shell with "10" and this value is picked up bycommandArgs
and fed intoargs[2]
, and the range commandx=1:10
executed by R successfully, etc etc.If you need to specify options with flags, (like -h, --help, --number=42, etc) you can use the R package optparse (inspired from Python): http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf.
At least this how I understand your question, because I found this post when looking for an equivalent of the bash getopt, or perl Getopt, or python argparse and optparse.
FYI: there is a function args(), which retrieves the arguments of R functions, not to be confused with a vector of arguments named args
Since
optparse
has been mentioned a couple of times in the answers, and it provides a comprehensive kit for command line processing, here's a short simplified example of how you can use it, assuming the input file exists:script.R:
Given an arbitrary file
blah.txt
with 23 lines.On the command line:
Rscript script.R -h
outputsRscript script.R -n blah.txt
outputs[1] "69"
Rscript script.R -n -f 5 blah.txt
outputs[1] "115"