Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Operating R from Java

Operating R from Java

First, install the package "Rserve" in R.

If you are using the RGui visual interface, you can complete this step in the menu bar under Packages - Install package(s). 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 Reserve is installed, there will be a library directory under the R root directory; find the Rserve/java directory inside it, and you will find 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 of the R system!

Step 1: Start Reserve

Enter R and type the following code to start Rserve:

library("Rserve")

Rserve()

If startup succeeds, R will output the path of Rserve.

Step 2: Write the Java program

First import the two jar libraries mentioned above.

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

We 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 a connection with Rserve

            rcon

=

new

RConnection

(

"127.0.0.1"

)

;

           

           

// The eval() function is used to make R execute R statements

           

// Here an m1 matrix is created

            rcon.

eval

(

"m1 = matrix(c(1, 2, 3, 4), 2, 2, byrow=TRUE)"

)

;

           

           

// The solve() function computes the inverse of the m1 matrix in R

           

// and returns the result; the asDoubleMatrix function can convert the data into

           

// a two-dimensional double 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

Obviously, the result is correct, but after all they are floating-point numbers, so the printed output may not look very neat; this does not affect the use of the data.