Operating 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 root directory of R, where you can find the Rserve/java directory. Inside this directory, you will find two files: REngine.jar and Rserve.jar.
These two files are the R interface libraries in Java.
Note: Java cannot use R functionalities independently without the R system!
Step 1: Start Rserve
Enter R and input the following code to start Rserve:
library("Rserve")
Rserve()
If the startup is successful, R will output the path of Rserve.
Step 2: Write a Java Program
First, import the two jar libraries mentioned earlier.
After importing, we recognize a key class: RConnection, which can be used to connect to Rserve.
Now, we will 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 a connection to 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 calculates the inverse of matrix m1 in R
// and returns the result. The asDoubleMatrix function converts the data
// into a double two-dimensional array in Java 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[0].length; j++)
System.out.print(m1[i][j] + "\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
Clearly, the result is correct, but since it involves floating-point numbers, the printed output might not be visually appealing, though it does not affect the use of the data.