Wednesday, July 23, 2014

How to run R from Shell script ?

http://stackoverflow.com/questions/2151212/how-can-i-read-command-line-parameters-from-an-r-script
http://stackoverflow.com/questions/5391124/in-r-select-rows-of-a-matrix-that-meet-a-condition
http://stackoverflow.com/questions/7201341/how-can-2-strings-be-concatenated-in-r

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 file
    args <- span=""> commandArgs(trailingOnly = TRUE)
    print(args)
    # trailingOnly=TRUE means that only your arguments are returned, check:
    # print(commandsArgs(trailingOnly=FALSE))
    
    start_date <- span=""> as.Date(args[1])
    name <- span=""> args[2]
    n <- span=""> as.integer(args[3])
    rm(args)
    
    # Some computations:
    x <- span=""> 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_Script%:
"C:\Program Files\R-3.0.2\bin\RScript.exe"
and use it in your batch scripts as %R_Script% .......
Differences between RScript and Rterm:

======================================================================
> colnames <- c="" col1="" col3="" div="" nbsp="">
> data[ , colnames] 
  col1 col3
1    1    4
2    2    5
3    3    6
> data[ , colnames] 
  col1 col3
1    1    4
2    2    5
3    3    6
> r <- colnames="" data="" div="" nbsp="">
> r
  col1 col3
1    1    4
2    2    5
3    3    6
> r[r$col1 == 2,]
  col1 col3
2    2    5
> # this is a comment line
> r[r$col1 == 2 || r$col1==3,]
[1] col1 col3
<0 rows=""> (or 0-length row.names)
> r[r$col1 == 2,]
  col1 col3
2    2    5
> r[r$col1 == 2 | r$col1==3,]
  col1 col3
2    2    5
3    3    6

No comments: