Using R code in Java Eclipse with rJava

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.



Introduction


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.

using R code in Java Eclipse with rJava


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.
using R code in Java Eclipse with rJava



Environment Variables


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

using R code in Java Eclipse with rJava



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



Eclipse Project and Class


Make a new project in Eclipse : File -> New -> Java Project .
using R code in Java Eclipse with rJava

Insert aRjava or your favorite name as Project name.
  • Project name : aRjava
using R code in Java Eclipse with rJava


Make a new class : File -> New -> Class .
using R code in Java Eclipse with rJava

Insert CRjava or your favorite name as Name.
  • Name : CRjava
using R code in Java Eclipse with rJava



Writing a Java code with rJava


Write a code using rJava in CRjava class file.
using R code in Java Eclipse with rJava

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://shleeai.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.
using R code in Java Eclipse with rJava

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...

In fact, this holds true when a project has one class file. When we add another class file, some settings are necessary for this another class file. Since this will be covered next post, let's forget it for a while.

Eclipse Project Settings - Run Configurations


Open Project --> Run As --> Run Configurations.
using R code in Java Eclipse with rJava

At first, we need to check whether Project and Main class are set to aRjava and aRjava.CRjava respectively.
using R code in Java Eclipse with rJava

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
using R code in Java Eclipse with rJava

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.
using R code in Java Eclipse with rJava


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

using R code in Java Eclipse with rJava


3) For aRjava, Add Projects... to Classpath Entries only if aRjava is absent in Classpath Entries.
using R code in Java Eclipse with rJava


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 ";".
using R code in Java Eclipse with rJava



Eclipse Project Settings - Configure Build Path...


As the setting for Run Configurations is completed, it's time to add settings on Configure Build Path....
using R code in Java Eclipse with rJava


In Libraries tab,
For JRI.jar, Add External JARs... to Classpath.
using R code in Java Eclipse with rJava

Now the setting for Eclipse Project is done completely.



Running and Results


When we rerun CRjava.class file, We can obtain correct results.
using R code in Java Eclipse with rJava

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\)


3 comments:

  1. why not just using StatET eclipse plugin ?

    ReplyDelete
    Replies
    1. Thank you for reply and good suggestion.
      Since I have no experience in using StatET eclipse plugin, I will try to learn and use it soon.

      Thanks again for the useful information.

      Delete
  2. 안녕하세요. 구글 블로그 사용자를 보네요

    ReplyDelete