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?
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[];
LoadJavaClass["java.lang.Runtime"]
and then
Runtime`getRuntime[]@
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.
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:32Run
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:48Run
works for you, all the better. I added anRLink
- based solution, which may be a bit heavy-handed compared toRun
(butRun
did not work for me on Windows - in the sense that it was blocking). $\endgroup$ – Leonid Shifrin Nov 29 '12 at 23:10Run["!...&"]
on windows with this little call:Import["!start \"\" /b /d \"" <> path <> "\" " <> program <> ".exe" <> args, "Text"]
, where you replacepath
,program
andargs
with the relevant strings. $\endgroup$ – Malte Lenz Nov 30 '12 at 10:14