R Java
# Working with R in Java
First, install the "Rserve" package in R.
If you are using the RGui graphical interface, you can complete this step in the menu bar under Packages - Install Packages. If you are using the pure R Console, you can use the following command:
install.packages("Rserve", repos = "https://mirrors.ustc.edu.cn/CRAN/")
After Rserve is installed, there will be a `library` directory in the R root directory. Find the `Rserve/java` directory within it, and you will discover two files: `REngine.jar` and `Rserve.jar`.
These two files are the R interface libraries for Java.
**Note:** Java cannot use R's functionality independently without the R system!
### Step 1: Start Rserve
Enter R and input the following code to start Rserve:
library("Rserve")Rserve()
If it starts successfully, R will output the path of Rserve.
### Step 2: Write the Java Program
First, import the two jar libraries mentioned earlier.
After importing, let's understand a key class: `RConnection`. This class can be used to connect to Rserve.
We will now use R in Java to perform an inverse matrix operation:
!(#)
## Example
import org.rosuda.REngine.Rserve.*;
public class Main {
public static void main(String[] args){
RConnection rcon =null;
try{
// Establish connection with Rserve
rcon =new RConnection("127.0.0.1");
// The eval() function is used to make R execute R statements
// Here, a matrix m1 is created
rcon.eval("m1 = matrix(c(1, 2, 3, 4), 2, 2, byrow=TRUE)");
// The solve() function in R calculates the inverse matrix of m1
// and returns the result. The asDoubleMatrix function can convert the data into
// a Java double 2D array to represent the matrix
double[][] m1 = rcon.eval("solve(m1)").asDoubleMatrix();
// Output the contents of the matrix
for(int i =0; i < m1.length; i++){
for(int j =0; j < m1.length; j++)
System.out.print(m1+"t");
System.out.println();
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(rcon !=null) rcon.close();
}
}
}
Execution result:
-1.9999999999999998 1.0 1.4999999999999998 -0.49999999999999994
Obviously, the result is correct, but since it is floating-point, the printed output might not look very neat, but it does not affect the use of the data.
YouTip