Reputation: 19905
Is it possible to do some simple calculations in R, with input from a Java program, and get the response into that Java program?
A typical example of this data exchange between Java and R is calculating the Probability Distribution Function (PDF) of an array of numbers (say a Java double[]
array).
From within a Java class, the array should be passed to R via the Java/R Interface (JRI) and the result of the calculation should not be a graphic plot (as JRI would do in a JFrame), but another array of values (or similar Java data structure) that would be retrievable from the same Java class, for further processing.
The JRI assignment part would look something like this:
Rengine re=new Rengine(new String [] {"--vanilla"}, false, null);
if (!re.waitForR())
{
System.out.println ("Cannot load R");
return;
}
double[] values = ... // The data values
re.assign("data", values);
So, the question is whether the data
array above could be processed in R as already described (e.g., for the PDF), with results returned back to the calling Java class, instead of graphically plotted by R.
Is that possible and, if yes, is there any example code demonstrating it?
Upvotes: 1
Views: 1165
Reputation: 301
The simplest method I can see for implementing this is to have Java run R using methods like this simple method or these more careful methods. R will send the output to stdout which can be picked up and parsed in Java.
See ?Rscript
in R to see the formatting for the system call to be run from Java.
A more robust method (one I've used) works by using Java (or whatever other program you're using) to save the R commands and data to one or more text files (perhaps one script.R and one or more data1.tab files), call R reading in the R script file, within R save the results to a text file, then have Java (or whatever) read the results and clean up. The downside here is speed, of course. If you can get the inline method (stdin/stdout) to work for you, it will be a lot faster.
While this doesn't point you to a JRI, it would be pretty easy to write a few functions in Java (or whatever) that provide such an interface for arbitrary R code and a collection of Java vectors/matrices that are automatically passed to R within the script using the format specified for the R function ?dump
.
Upvotes: 1