Site icon R-bloggers

Using R code in Java Eclipse with rJava

[This article was first published on K & L Fintech Modeling, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This post shows how to use R code in Eclipse IDE for Java with rJava package. But this work requires several environment setting which is a little bit confusing. Although there are some good posts regarding this issue, we use a step by step guide with detailed screen captures for clear understanding.


Using R code in Java Eclipse with rJava


Occasionally we would encounter some problems which are not easy to implement in Java. Among them are financial or econometric model estimation or optimization, to name a few. But in many cases, these problems are easily solved in R thanks to its various packages which are supported by worldwide experts.

This leads to the necessity of the connection between R and Java. For this purpose, rJava package provides this interface functionality but environment setting is not easy. 

With detailed screen captures, let’s find the efficient way to use rJava in Eclipse. For convenience, we assume R and Eclipse are installed already.


Installing rJava


we need to install rJava package in R studio.



We need to know the directory where rJava package is installed. In our case, this directory is as follow. (this is dependent on your Windows system)

C:\Users\shlee\Documents\R\win-library\4.0

The following figure displays files of rJava/jri directory.

Environment Variables


Find “Edit the system environment variables” and open System Properties box, and click Environment Variables … button.


Add Path as a new variable in System Variables as follows.
  • Path : C:\Users\shlee\Documents\R\win-library\4.0\rJava\jri\x64;

Eclipse Project and Class


Make a new project in Eclipse : File -> New -> Java Project .

Insert aRjava or your favorite name as Project name.
  • Project name : aRjava


Make a new class : File -> New -> Class .

Insert CRjava or your favorite name as Name.
  • Name : CRjava

Writing a Java code with rJava


Write a code using rJava in CRjava class file.

The above Java code is to call R command for the eigen decomposition and return eigenvector. Matrix multiplication with its transpose ensures the positive definite. The full Java code is as follows.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//=========================================================================#
// Financial Econometrics & Derivatives, ML/DL using R, Python, Tensorflow  
// by Sang-Heon Lee 
//
// https://kiandlee.blogspot.com
//————————————————————————-#
// rJava example with built-in R commands
//=========================================================================#
package aRjava;
 
import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.REXP;
 
public class CRjava {
    public static void main(String[] args) {
 
        // Launch and Start rJava
        Rengine re=new Rengine(new String[] { “–vanilla” }, falsenull);
 
        // Input parameters
        int nvar = 3;
 
        // R commands through rJava
        re.eval(“ma <- matrix(rnorm(“+nvar+“,”+nvar+“),”+nvar+“,”+nvar+“)”);
        re.eval(“mb <- ma%*%t(ma)”);
        re.eval(“eg <- eigen(mb)”);
        REXP x = re.eval(“eg$vectors”);
        
        // Result : raw output
        System.out.println(“Result as a raw output”);
        System.out.println(x+“\n”);
        
        // R matrix –> Java 2D array
        double[][] mout = x.asDoubleMatrix();
 
        System.out.println(“Result as a 2D array”);
        for(int i = 0; i<nvar; i++) {
            for(int j = 0; j<nvar; j++) {
                System.out.print(String.format(“%2.5f”, mout[i][j]) + ”   “);
            }
            System.out.println(“”);
        }
 
        // end rJava
        re.end();
    }
}
 
cs

When we run the above Java code, we encounter the following errors which are obstacles in the way. Hence, we need to some settings for Eclipse.

But this first running this project is important because after this trial, Run Configuration (which will be explained later) can identify this project. 


Eclipse Project Setting


This is the highlight section of this post. This setting seems so complicated but let’s do it.

The bottom line for the Eclipse setting is that we have only to add two settings on our project not class files.

  • Project –> Run As –> Run Configurations
  • Project –> Build Path –> Configure Build Path…

Eclipse Project Settings – Run Configurations


Open Project –> Run As –> Run Configurations.

At first, we need to check whether Project and Main class are set to aRjava and aRjava.CRjava respectively.
 

In Arguments tab, VM arguments is filled as follows.
  • VM arguments : -Djava.library.path=C:\Users\shlee\Documents\R\win-library\4.0\rJava\jri\x64

In Dependencies tab, 

It is most important to distinguish between Modulepath Entries and Classpath Entries with respect to kind of jar file and project.


1) For JRIEngine.jar and REngine.jar, Add External JARs… to Modulepath Entries.


2) For JRI.jar, Add External JARs… to Classpath Entries


3) For aRjava, Add Projects… to Classpath Entries only if aRjava is absent in Classpath Entries.

In Environment tab, Add three directories in the following way.
 
  • LD_LIBRARY_PATH : C:\Program Files\R\R-4.0.3\bin;C:\Program Files\R\R-4.0.3\library;C:\Users\shlee\Documents\R\win-library;
  • PATH : C:\Program Files\R\R-4.0.3\bin\x64;C:\Users\shlee\Documents\R\win-library\rJava\jri\x64;
  • R_HOME : C:\Program Files\R\R-4.0.3

Here, in case of R_HOME, there is no “;”.
 

Eclipse Project Settings – Configure Build Path…


As the setting for Run Configurations is completed, it’s time to add settings on Configure Build Path….


In Libraries tab, 

For JRI.jar, Add External JARs… to Classpath.


Now the setting for Eclipse Project is done completely.

Running and Results


When we rerun CRjava.class file, We can obtain correct results.

Although setting for rJava in Eclipse is so complicated, we try to summarize this setting process with many detailed screen captures for clear understanding. 

We expect that rJava is quite useful when R is more suitable for some complicated calculations or estimations when Java is a main program.

Next time, we will use rJava for more complicated problems. \(\blacksquare\)

To leave a comment for the author, please follow the link and comment on their blog: K & L Fintech Modeling.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.