English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Operation R in Java

Firstly, install the software package "Rserve" in R.

If you are using the RGui graphical interface, in the menu bar, under Programs - The installation program can complete this step. If you are using a pure R Console, you can use the following command:

install.packages("Rserve", repos = "https://mirrors.ustc.edu.cn/CRAN/

After the installation of Reserve is complete, there will be a library directory under the root directory of R, where you can find Rserve/Navigate to the java directory, and you will find two files: REngine.jar and Rserve.jar under the directory.

These two files are the R interface libraries in Java.

Note:Java cannot use R's features independently without the R system!

First step: start Rserve

Enter R and input the following code to start Rserve:

library("Rserve")
Rserve()

If the start is successful, R will output the path of Rserve.

Second step: write a Java program

Firstly, import the two JAR libraries mentioned earlier.

After importing, we get to know a key class: RConnection, which can be used to connect to Rserve.

Now we use R in Java to perform an inverse matrix operation:

import org.rosuda.REngine.Rserve.*;
public class Main {
    public static void main(String[] args) {
        RConnection rcon = null;
        try {
            // Establish a connection with Rserve
            rcon = new RConnection("127.0.0.1);
            
            // eval() function is used to let R execute R statements
            // Here is a m1 matrix
            rcon.eval("m1 = matrix(c(1, 2, 3, 4), 2, 2, byrow=TRUE
            
            // solve() function in R to find m1 the inverse matrix of the matrix
            // and return the result, the asDoubleMatrix function can convert the data into
            // Double two-dimensional array in Java to represent the matrix
            double[][] m1 = rcon.eval("solve(m1).asDoubleMatrix();
            
            // Output the content 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 is a floating-point number, the output may not look very good, which does not affect the use of the data.