0

I want to run a R script from matlab.

I can run the R code perfectly from cmd using:

cd "C:\Program Files\R\R-3.1.3\bin\x64"
R CMD BATCH "C:\Users\name\Desktop\Code.R"

However in Matlab I am not sure how to run this two instructions. First, I noticed that I could use:

system('cd "C:\Program Files\R\R-3.1.3\bin\x64"')

to run a commnand line command. However I need to run two. And making:

system('cd "C:\Program Files\R\R-3.1.3\bin\x64"')
system('R CMD BATCH "C:\Users\name\Desktop\Code.R"')

does not work.

I also saw this post about running multiple command line instructions in a single line, but also that did not work.

Anyone knows how to do it?

Community
  • 1
  • 1
phdstudent
  • 1,060
  • 20
  • 41

2 Answers2

2

Your script should generally not care where it’s executed. So you don’t need the cd statement at all:

system('"C:\Program Files\R\R-3.1.3\bin\x64\R.exe" CMD BATCH "C:\Users\name\Desktop\Code.R"')

Be careful thought that the R path might not always be the same … it’s probably safer to find R’s location programmatically. Though how to do that in Matlab on Windows, I don’t know.

Furthermore, I honestly don’t really know why R CMD BATCH even exists but I strongly recommend using RScript instead. It works much nicer for a number of reasons.

The code then becomes:

system('"C:\Program Files\R\R-3.1.3\bin\x64\Rscript.exe" "C:\Users\name\Desktop\Code.R"')
Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
-3

Try to use dos command instead of system.

Andrei Davydov
  • 315
  • 1
  • 7