Passing RScript arguments from Command Line
There may be situations where you might want to execute R scripts from command line and passing appropriate arguments as batch. So here is an example below
C:\Users\UserName\Documents\>
"C:\Program Files\R\R-3.3.0\bin\RScript.exe" args.R 2016-08-01 28 1 30 > args.t
In the above I have specified the location of the RScript.exe on my local computer and args.R is the R script that I want to run from command line and the arguments are 2016-08-01 which is a Date in the format yyyy-mm-dd, then 28 and then 1 and 30 and the result of the execution will get saved in args.txt file which is the output of the execution.
Here is the sample R script code below
#READ THE ARGUMENTS
args <- commandArgs(TRUE)
# test if there is at least one argument: if not, return an error
if (length(args)==0) {
stop("First parameter is a required argumenst.n", call.=FALSE)
}
print(args)
#GETTING ARGUMENT OF THE R SCRIPT.
startDate <- as.Date(args[1])
sId <- eval(parse(text=args[2]))
min <- eval(parse(text=args[3]))
max <- eval(parse(text=args[4]))
#write the variables as observations of a dataframe
columnNames <- c('sId', 'startDate', 'min', 'max')
columnValues <- c(sId, startDate, min, max)
df = data.frame(columnNames, columnValues)
str(df)
print(df)
write.csv(df, file = "C:/args.csv", row.names=F)
The data frame created above gets saved as a csv file for review. Please note internally Date is represented as integer in R.