views:

645

answers:

4

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?

+1  A: 

you need littler (pronounced 'little r')

Dirk will be by in about 15 minutes to elaborate ;)

JD Long
I was seven minutes late. Must have been bad traffic on the Intertubes.
Dirk Eddelbuettel
either that or you are getting old. ;)
JD Long
I clearly didn't read his question well. -1 for me failing to see the Windows requirement
JD Long
+9  A: 

A few points:

  1. Command-line parameters are accessible via commandArgs(), so see help(commandArgs) for an overview.

  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.

Dirk Eddelbuettel
+2  A: 

Dirk answer is everything you need. I give you small example.

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

  • exmpl.bat:

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

    args <- commandArgs(trailingOnly = TRUE)
    print(args)
    # trailingOnly=TRUE means that only arguments after --args are returned
    # if trailingOnly=FALSE then you got:
    # [1] "--no-restore" "--no-save" "--args" "2010-01-28" "example" "100"
    
    
    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 result you got:

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

Just to add - you could add environment variable %R_TERM%:

"C:\Program Files\R-2.10.1\bin\Rterm.exe" --no-restore --no-save

and use it in your batch scripts as %R_TERM% --args .......

Marek
+1  A: 

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.

Hrishi Mittal