Get Argument Value from Command Line in R

Sometimes, you may want to run R Script by using command line. In this way, you can write a bash script and schedule a task everyday. In addition you can also pass different arguments to the R program.

Create a R script “GetARgument.R”:

args <- commandArgs(TRUE)
if(length(args) == 0){
        print("No arguments!")
        # give a default value
        date <- 20140502

}else{
        for(i in 1:length(args)){
                eval(parse(text=args[[i]]))
        }
}

print(date)

Run the following command:

R CMD BATCH  '--args date=20140801' GetArgument.R 

The program will generate an output file - "GetArgument.Rout". In this file, you will see all the output in the console.

Leave a Comment