I would like to run a batch job from within the current Mathematica .m file using "R CMD BATCH &" (the job runs in the background when Mathematica proceeds with the current calculations. How can I do that in Mathematica 9?

  • 1
    $\begingroup$ Run does not seem to be asynchronous to me, so I am not sure if this would work (correct me if I am wrong) $\endgroup$ – Leonid Shifrin Nov 29 '12 at 22:32
  • 1
    $\begingroup$ @preeti I meant that Run seems to wait until the result is ready (the batch), and block the computations of the main process. May be I am wrong, but that's what I saw on Windows. Re: RLink Yes, I wrote it, and I hope to post an answer based on it soon, just have to resolve one glitch. $\endgroup$ – Leonid Shifrin Nov 29 '12 at 22:48
  • 1
    $\begingroup$ @preeti Well, if Run works for you, all the better. I added an RLink- based solution, which may be a bit heavy-handed compared to Run (but Run did not work for me on Windows - in the sense that it was blocking). $\endgroup$ – Leonid Shifrin Nov 29 '12 at 23:10
  • 1
    $\begingroup$ @LeonidShifrin You can get functionality similar to Run["!...&"] on windows with this little call: Import["!start \"\" /b /d \"" <> path <> "\" " <> program <> ".exe" <> args, "Text"], where you replace path, program and args with the relevant strings. $\endgroup$ – Malte Lenz Nov 30 '12 at 10:14
  • 1
    $\begingroup$ @MalteLenz Interesting. Thanks for pointing this out, will try. $\endgroup$ – Leonid Shifrin Nov 30 '12 at 10:49

Here is a possible RLink - based solution. I will use Windows version, since it is easiest for me right now to test on Windows, but it should work on other platforms as well with a few obvious modifications.

First, here is a sample Mathematica script I used to test:



     testdata <- rnorm(100)


which I stored in C:\\Temp\\script.m. The R code inside models your batch script code. The Pause[10] models some running time for the batch script. Now, here is what you do:


and then

      FileNameJoin[{$InstallationDirectory, "math.exe"}], 

This launches a separate process, which would execute the Mathematica script in C:\\Temp\\script.m, which, in turn, will load RLink and execute your R batch script.

This code returns immedaitely, so that your main kernel is not blocked, and you can compute with it regardless of whether or not the batch job has completed.

In fact, while I did not do it here, this can be further automated,so that you run your batch script from within Mathematica, first saving it to a temporary file. I may add this automation layer later.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.