# Mathematica 9 Linking with R

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?

-
Run does not seem to be asynchronous to me, so I am not sure if this would work (correct me if I am wrong) – Leonid Shifrin Nov 29 '12 at 22:32
@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. – Leonid Shifrin Nov 29 '12 at 22:48
@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). – Leonid Shifrin Nov 29 '12 at 23:10
@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. – Malte Lenz Nov 30 '12 at 10:14
@MalteLenz Interesting. Thanks for pointing this out, will try. – 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:

Needs["RLink"]
InstallR[]

Pause[10]

REvaluate["{
testdata <- rnorm(100)
dim(testdata)<-c(10,10)
write.table(testdata,\"C:/Temp/testRdata.dat\")
}"]

Quit


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:

Needs["JLink"];
InstallJava[];


and then

RuntimegetRuntime[]@
exec[{
FileNameJoin[{\$InstallationDirectory, "math.exe"}],
"-script",
"\"C:\\Temp\\script.m\""}
]


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.

-