Wednesday, August 29, 2012

Pass Parameters from Linux/Unix Shell to R


Suppose there are two parameters (START, END) to be carried from Linux shell (bash) script to R. The trick is to use the argument "--args START=1 END=10" in a SGE jobscript to submit a R job in the BATCH mode: qsub test.sh
R CMD BATCH --no-save --no-restore '--args START=1 END=10' sample.R

Here is a template test.sh
#!/bin/bash 
#$ -cwd 
#$ -N NAME_OF_JOB
#$ -M YOUR_EMAIL_ADDRESS
# email me when the job e-ends,a-aborts,s-suspends
#$ -m eas
#$ -S /bin/sh 
# Combining output/error messages into one file
#$ -j y

R CMD BATCH --no-save --no-restore '--args START=1 END=10' sample.R
 In the sample.R program, it should contain
#======================================================== 
# At the beginning of R, it should contain 
#======================================================== 
## First read in the arguments listed at the command line 
args = (commandArgs(TRUE)) 
## args is now a list of character vectors 
if (length(args)==0) {
                                print("No arguments supplied.") 
                                ## Supply default values 
                                START = 0 
                                END = 0 
                               }
else {
        for (i in 1:length(args)) 
                                            eval(parse(text=args[[i]])) 
                                           } 
       } 
#======================================================== 
print(START) 
print(END) 
#======================================================== 
# Main R program 
#======================================================== 
for (i in START:END) { ... }
Reference Click Me

1 comment: