Skip to main content

Using R Programming Language inside Java

Hi,

This tutorial walks you through using R programming language inside a java program. R is a powerful programming language for Machine Learning and Data Mining. It contains implementation of various Machine Learning algorithms. Recently i had a situation where i was supposed to use these machine learning algorithms inside my java program. I searched the web but the stuff i found was not of much help. Thus i thought of putting the same in the form of this tutorial.

This tutorial is not intended to teach you R language. It is only to help you integrate R to Java and then to use R functions inside a Java program.

Pre-requisite:
Following things are needed to be pre-configured on your system to use R in Java program:

1. R workbench: R has got a console known as RGui where R commands/programs could be executed. To install RGui simply go to http://cran.r-project.org/bin/windows/base/ and download the 'Download R 3.0.2 for Windows (52 megabytes, 32/64 bit)'. Simply double click the exe and install it. One thing to be noted is that, try to install RGui in some other drive other than C:\ drive because C:\ drive has some permission issue.
(I installed RGui under 'D:\ProgramFiles\' so further in this tutorial i'll be refering to this location. You could modify the location accordingly. )

2. JDK 1.7 or above: Simply install jdk 1.7 and add it to the 'PATH' of your system.
3. Eclipse: You could use any version of eclipse. For this tutorial i have used Eclipse Indigo.
4. Proxy less internet connection to your system: As will be downloading few packages for RGui workbench you need a proxy less internet connection (else you have to manually download the .zip packages and configure them in RGui).

That is all you need to get going with using R in Java.

Getting Started:

With the above ground we will start with configuring R with Java. Following steps illustrate the process:

STEP 1. Firstly we need to add the package rJava to RGui. rJava provides the APIs that help in integrating R and Java with each other (to know more about rJava refer the URL http://rforge.net/JRI/). To install rJava in RGui follow following steps:
  1. Open RGui, you will get a screen like this:

2.  New we need to install rJava in RGui. To do this select Packages->Install package(s)... menu in RGui. You will see like a window like this
This window asks the mirror to be used to download rJava. Select USA (KS) from the list (as it has latest updates). Click Ok.

3. You will see a new window that lists the package to be installed. From the list select rJava (shown in red box in figure below).
Click OK and the package will be downloaded to your system.

4. Next we need to load the downloaded package. For this select menu item Packages->Load package... and you will see a list of packages present. There you will find rJava which you downloaded just now. Simply select rJava from the list and click OK. The package will be loaded to RGui.

That is all we need to configure in RGui. Next we will be configuring the PATH to locate various libraries.



STEP 2: Now we need to configure the PATH environment variable. To do this follow the following steps:
(These steps are for windows. To configure the same in linux you could use bash.rc)

1. Right click on MyComputer.
2. Select Advance system settings.
3. Select Environment Variables.
4. Under System variables section select PATH variable and select Edit... button and add following path to the existing path
 "D:\ProgramFiles\R\R-3.0.2\bin\i386;D:\ProgramFiles\R\R-3.0.2\library\rJava\jri\i386;"
Note here that as i have installed R in my D:\ drive i have used that path, if you have installed it somewhere else then use that path. so the generic paths will be:
 "<YOUR_R_HOME>\bin\i386;<YOUR_R_HOME>\library\rJava\jri\i386;"

Note: As R uses some native libraries, thus when we try to execute R from inside a java program we need access to some DLL files like: R.dll, jri.dll etc. The paths above are used to locate these .dll files.

 (if PATH is not already present then select New... button and in variable name enter PATH and in Variable value enter "D:\ProgramFiles\R\R-3.0.2\bin\i386;D:\ProgramFiles\R\R-3.0.2\library\rJava\jri\i386;"  )

5. click Ok, OK, OK and your paths are set.


STEP 3: Now that we have configured everything we simply need to create a java program and use R inside it. Following steps guide you through the process:

1. Start eclipse.
2. Create a new Java Project and name it RBlog.
3. Right click on RBlog and  select Build Path->Configure Build Path...
4. Select Add External JARs...
5. On the JAR Selection dialog go to path 'D:\ProgramFiles\R\R-3.0.2\library\rJava\jri' or if you installed R somewhere else then use "<YOUR_R_HOME>\library\rJava\jri".
6. In this folder you will find three jar files:
    (i) JRI.jar
    (ii) JRIEngine.jar
    (iii) REngine.jar
  select all these 3 jars and select Open. Then click OK and these jars will be added to your project.
After this your project should look like:
Now that we have configured our eclipse project we need to add the source code.

7. add package 'rInsideJava' to the src folder of the project.
8. add Main.java inside package rInsideJava.
9. Final structure of you project should look like this:
10. now add following source code to Main.java
package rInsideJava;

import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;

import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.JRI.JRIEngine;

public class Main {

public static void main(String a[]) throws REngineException
{
Rengine re = new Rengine (new String[]{"--no-save"}, false, null);
re.eval("data=sqrt(11)");
REXP result = re.eval("data");
System.out.println(result.toString());
re.end();
}
}

The output of the execution will be 

[REAL* (3.3166247903554)]

Note: Above code contains a simple class. The code involving R language syntax is highlighted using yellow. First line highlighted in yellow calculates square root of 11 and stores the result is variable data. In second yellow line we simple retrieve the value of R variable data and store it in result. You could experiment with using other R commands. 

I hope this tutorial helps in integrating R with Java.
Please feel free to submit and queries and suggestions.

Thanks

Comments

  1. It helped me to start with R. Thanks,

    ReplyDelete
  2. Hi Sir,

    Many thanks for the blog.May i know more examples on running R script through java for instance reading a csv file and caliculating the meanmedian mode and drawing plots for the results through java using R

    ReplyDelete
    Replies
    1. Hi Kishore, this post demonstrates how to integrate R with JAVA. However if you need to implement some complex logic in R then it will be better that you code the logic concerning R in a R file and save it with .R extension and using 'eval()' simply call that file. Like if your file is saved on D:\ drive with name temp.R then simply call it like re.eval("D:\\\\temp.R"). Notice four '\' they have to be in the same way.
      I hope this will help you.

      Delete
    2. Hi Kishore, I have also posted a turotial on how to calculate mean for a column of CSV file in another post http://rajeev0401.blogspot.in/2014/12/accessing-r-script-from-java.html

      You could refer this link and similarly calculate other measures. I hope this will be of help.

      Delete
  3. hi this is useful but i got error while running cannot find jri native library.how can i fix it in windows 7.how to add in jri native library in java.library.path.

    ReplyDelete
    Replies
    1. try installing 'rJava' package in r. It should remove this error.

      Delete
  4. can any one help me out with a script for finding p-value by giving input as a text file??

    I have been doing it for past 1 week but not getting how to do so??

    and I am a beginner also..... so getting things late......


    ReplyDelete
  5. Can any one tell me how to call rgeos function on java ?

    ReplyDelete
  6. Hi,

    I followed all the steps you explained above and I am getting the following error:

    Can't load IA 32-bit .dll on a AMD 64-bit platform

    ReplyDelete
    Replies
    1. Your systems seems to be 64-bit, however the dll you are referring to is 32-bit. Try to use a 64-bit dll.

      Delete
  7. Hi this code is not throwing any exception but is not displaying anything in console.What should I change to get it working ?

    ReplyDelete
  8. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    rprogramming training in bangalore

    ReplyDelete
  9. So valuable post.Thank you to share your knowledge with us.Its really good to the connectivity in java and big science.
    mobile service center in chennai

    ReplyDelete
  10. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.
    java training in chennai

    java training in tambaram

    aws training in chennai

    aws training in tambaram

    python training in chennai

    python training in tambaram

    selenium training in chennai

    selenium training in tambaram

    ReplyDelete

Post a Comment

Popular posts from this blog

Uploading a binary file to RESTful web service in java using Jersey

Hi, Recently I had a situation where I was supposed to upload a binary file to a server side RESTful web service created in Jersey. I faced a lot of trouble in doing so because always one or the other part of the hood was not working properly. The following post gives a step by step process as how to create a RESTful service that accepts uploaded binary files. Pre-requisites: 1. A running RESTful service based on Jersey. 2. An HTML page with file upload component. 3. Tomcat 7 as web server. 4. Eclipse indigo. Note: Let us suppose that tomcat is running on same machine on which the HTML client is present. So we will be using the base domain URL as ' http://localhost:8080/ '. If your service and client are located on different instances of tomcat then replace the localhost part of the URL with the IP address of the machine on which the REST service is running. Step 1 (Eclipse setup): a. Create a 'Dynamic Web Project' in eclipse indigo. Let us say that thi

Creating a JAX-WS Web Service and Client using Eclipse Indigo

Creating a JAX-WS Web Service and corresponding client is a very trivial task. However I faced various problems while doing the same mainly while creating a client for the web service. This was mainly because the contents I found on the Internet were in a distributed manner. So I thought of creating a tutorial which binds all the concepts at one place. So this tutorial does not teaches indepth concepts of web services. Instead it guides as how to create a Web Service and a seperate client. Software Requirements: 1. Eclipse Indigo. Note: To download Eclipse Indigo follow the link http://www.eclipse.org/downloads/. Then select 'Eclipse IDE for Java EE Developers'. Process: We will proceed with the creation of web service and client in following two steps: 1. Creating Web Service 2. Creating client to consume web service. 1. Creating Web Service: Creating of a JAX-WS web service is not a very tough task. We simply create a class(normal Java class) and define certai