How can I read command line parameters from an R script? How can I read command line parameters from an R script? r r

How can I read command line parameters from an R script?


Dirk's answer here is everything you need. Here's a minimal reproducible example.

I made two files: exmpl.bat and exmpl.R.

  • exmpl.bat:

    set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"%R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1

    Alternatively, using Rterm.exe:

    set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"%R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
  • exmpl.R:

    options(echo=TRUE) # if you want see commands in output fileargs <- commandArgs(trailingOnly = TRUE)print(args)# trailingOnly=TRUE means that only your arguments are returned, check:# print(commandArgs(trailingOnly=FALSE))start_date <- as.Date(args[1])name <- args[2]n <- as.integer(args[3])rm(args)# Some computations:x <- rnorm(n)png(paste(name,".png",sep=""))plot(start_date+(1L:n), x)dev.off()summary(x)

Save both files in the same directory and start exmpl.bat. In the result you'll get:

  • example.png with some plot
  • exmpl.batch with all that was done

You could also add an environment variable %R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"

and use it in your batch scripts as %R_Script% <filename.r> <arguments>

Differences between RScript and Rterm:


A few points:

  1. Command-line parameters areaccessible via commandArgs(), sosee help(commandArgs) for anoverview.

  2. You can use Rscript.exe on all platforms, including Windows. It will support commandArgs(). littler could be ported to Windows but lives right now only on OS X and Linux.

  3. There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.

Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.


Add this to the top of your script:

args<-commandArgs(TRUE)

Then you can refer to the arguments passed as args[1], args[2] etc.

Then run

Rscript myscript.R arg1 arg2 arg3

If your args are strings with spaces in them, enclose within double quotes.