- Calling R functions from java
- Assigning values to R objects from Java
- Retrieving values from R into Java
Calling R functions from java
The org.rosuda.JRI.Rengine class has methods that allow calling R functions from Java. There are two ways to execute functions. Either call
each function using the Rengine, or open up a console to R.We would normally want to do the former. There are two kinds of API calls from Java to R.
High level and low level. It is preferable to use the high level calls when possible, however if low level calls have to be made then make sure to
apply synchronization to the method calls. Also only one instance of Rengine can be created, since the API does not allow creating multiple Rengine
instances from different threads. (no parallel programming support)
eval(String s,boolean convert)
This is probably the most important method of this API. ‘s’ is the expression that will be parsed and evaluated. The boolean ‘convert’
specifies whether the resulting REXP is empty(false) or contains the native implementation of the result. The example below creates a variable x,
finds and prints its mean
re.eval("x=c(1:10)"); double d = re.eval("mean(x)").asDouble(); System.out.println(d); // prints 5.5
Assigning Value to an R variable.
The eval function would not be very helpful if there was no way to pass values values to the R functions. For example, lets say you want to use the
power of R to calculate the mean of 10 numbers. Ok, you dont look convinced, i should probably get a better example. How about fitting points to a
linear equation y = mx+c. y and x are arrays passed to R. ‘eval’ is used to fit y and x to y=mx +c and m and c are brought back to R. Here’s
how we do it. We use the re.assign(“variable”,value) to assign a value to the R variable.
// Assign y to similarly named variable in R re.assign("y", y); // Lets see if it was assigned correctly System.out.println(Arrays.toString(re.eval("y").asDoubleArray())); // output [11.1, 13.2, 15.6, 27.4, 39.2, 113.1, 135.1] // Assign x to similarly named variable in R re.assign("x", x); // fit to y=mx+c re.eval("a=lm(y~x)"); // lets print the values RVector fit = re.eval("a").asVector(); System.out.println("The intercept is " + fit.at(0).asDoubleArray()); // prints The intercept is -19.60087719298246 System.out.println("The slope is " + fit.at(0).asDoubleArray()); // prints The slope is 8.481140350877192