0

I need to do the following:

1) From an R script (lets call it sample1.r), I will get a variable updated and a vector dates.
2) Now what I need to do is, if a condition satisfies (which is if updated == 1), I need to run a batch file of R scripts by passing arguments from the vector dates. Batch file of R scripts will look something like this.

Rscript D:/sample2.r "2015-05-01 00:00:00" dates[1] dates[2]    #statements 1
Rscript D:/sample2.r "2015-05-11 00:00:00" dates[2] dates[3]    #statements 2
Rscript D:/sample2.r "2015-05-21 00:00:00" dates[3]             #statements 3  

As you can see above, I am creating a batch file if a condition satisfies. For this first I am getting a vector dates and then passing the elements of this vector as arguments to the a script sample.r. I am passing 2 arguments to first 2 runs and 1 argument to the 3rd run.

As a solution to this I can create these statements in R itself using paste0 function, but after that how do I convert these statements into a batch file and trigger them from command prompt only when the condition satisfies? There may be an easier solution available but I am not aware of it. Can someone please help me this?

user3664020
  • 2,980
  • 6
  • 24
  • 45

1 Answers1

0

You can use sourceto call external scripts.

if(update == 1){
    source("D:/sample2.r")
    FunctionName("2015-05-01 00:00:00", dates[1], dates[2])
    FunctionName("2015-05-11 00:00:00", dates[2], dates[3])
    FunctionName("2015-05-21 00:00:00", dates[3])
}

source will call and run the external script. If you wrote your script without functions, it will run the script completely. In which case I would recommend splitting it in functions. This way you can just call any function names you want to call inside that script. You could just write an if-statement to call the script and functions. Note: This may give conflicts if both scripts contain the same function names, e.g. main.

If you want to call the script and passing your local variables:

source("D:/sample2.r", local=TRUE)

However if you want to call the scripts in the way you mentioned before, you can use system

if(update == 1){
    system(paste('Rscript D:/sample2.r "2015-05-01 00:00:00"', dates[1], dates[2], sep=" "))
    system(paste('Rscript D:/sample2.r "2015-05-11 00:00:00"', dates[2], dates[3], sep=" "))
    system(paste('Rscript D:/sample2.r "2015-05-21 00:00:00"', dates[2], sep=" "))
}
Bas
  • 1,066
  • 1
  • 10
  • 28