I am developing a Java based web application which needs to use R to perform some calculations. I've been able to install and configure rJava/JRI properly, but I'm stuck at this point: when I call R from a console app, it always works nice, however when I call R from a Servlet (or a Spring bean, I tried both) and this R code has a "source('r_script.R')" instruction, it works nice only the first call; the 2nd call returns NULL inside REXP, and 3rd call makes REngine hang. This is my code:
In Java servlet:
String rScriptUrl = this.getClass().getClassLoader().getResource("example1.R").getFile();
File rScriptFile = new File(rScriptUrl);
if (!rScriptFile.exists()) {
System.err.println("R script does not exist!");
return;
}
System.out.println("Loading REngine...");
Rengine re = new Rengine(new String[]{"--vanilla"}, false, null);
System.out.println("Rengine created, waiting for R");
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
System.out.println("R loaded!");
String rScriptPath = rScriptFile.getAbsolutePath();
rScriptPath = rScriptPath.replace("\\", "/");
String expr = String.format("source('%s')", rScriptPath);
re.eval(expr);
REXP result = re.eval("f1(10, 2)");
if (result != null) {
System.out.println(">>>>>> result from R: " + result.asDouble());
} else {
System.err.println(">>>>>> result is NULL");
}
re.end();
And example1.R contains:
f1 <- function(a, b) { return(a / b) }
So, trying this exact example in a Java console app will work nice always. R function "f1" executes and returns "5" as expected. If I call R from the servlet but not use "source('example1.R')", for example executing re.eval("2 * 3"), it runs OK as well and I get 6. But if I call "source('example1.R')" and run
REXP result = re.eval("f1(10, 2)");
the first run returns 5 properly, second run (just pressing F5) returns NULL, and 3r run code hangs at
Rengine re = new Rengine(new String[]{"--vanilla"}, false, null);
Can anybody put some light on this? Any ideas?
Thanks a lot, Marcos