Translate

Tuesday, 25 October 2016

Passing parameters to R script from command line


To pass parameters to the R script when running the script from the command line, commandArgs( ) can be used.

Example: 

Save the below script in a file called 'DateRange.r'

Para <- commandArgs() 
DATE <- as.Date(as.character(Para[6]), format = "%Y%m%d")
N <- as.numeric(Para[7])
DateRge <- data.frame(Date = seq(from = DATE, length.out = N, by = 1), Value = rnorm(N))

Then, run the below command with the parameters inserted at the end


For Windows

If the below path is saved in your environment variable, you can simply use 'Rscript' without writing out the full path.

"C:\Program Files\R\R-3.2.3\bin\Rscript.exe" DateRange.r [date in yyyymmdd format (DATE)] [length of sequence (N)] 

"C:\Program Files\R\R-3.2.3\bin\Rscript.exe" DateRange.r 20161005 5
will return:
       Date       Value
 2016-10-05  1.61637011
 2016-10-06 -0.08534756
 2016-10-07 -2.24108808
 2016-10-08  0.05773242
 2016-10-09  0.73725642 


For Linux
 
Similar to Windows, you can use Rscript command

Rscript DateRange.r yyyymmdd N 

Rscript DateRange.r 20161005 5 
        Date      Value
 2016-10-05 -0.7931385
 2016-10-06 -0.4229764
 2016-10-07 -0.3338677
 2016-10-08 -1.0844999








No comments:

Post a Comment