Skip to main content

Accessing R script from Java

R is powerful language for statistical analysis and Machine Learning. Java is best suited to develop enterprise applications. Integrating both could lead to developing powerful analytic applications. In this tutorial we are going to call a R script from java, then pass the parameters from java to R and fetch back the results from R to Java.

Problem Statement: In this tutorial we have a csv file 'data.csv' having 4 columns and we need to calculate mean of few user defined columns. To calculate the mean we will be using and then we will pass the calculated mean back to Java.

Pre-requisites:
 1. You should know how to integrate R with Java. For that you could consult the tutorial http://rajeev0401.blogspot.in/2013/10/using-r-programming-language-inside-java.html

Code Files:
We will be needing following files:
1. data.csv: file having data that will be used in R script.
2. config.R: this file contains the configuration (vector having column index) to be used in 'test.R'.
3. test.R: file having R script. 3
4. Main.java: file having Java code to integrate R with Java.

The structure of the above mentioned files is mentioned below:

1. data.csv : This file contains the actual data that will be used in R script. This file contains 4 columns as follows:
0.556,0.949,8.302,10.000
0.152,2.893,6.585,2.000
0.162,2.901,3.760,8.000
1.975,1.720,1.141,8.000

2. config.R : Any variable that needs to be used in R script, called from Java code, has to be predefined.
Before we execute 'test.R' from java we need to define the name 'colVector' that will hold the indicies
of columns for which mean is to be calculated. To do that we will define a 'colVector' in 'config.R'

colVector=c()
Just copy this line to an empty notepad and save it with name 'config.R'.

3. test.R : This file contains the main logic of calculating mean of user defines columns.

# Include this library to use function 'fread', that is used to read data from a csv file.
library(data.table)

# This variable will hold the mean of selected columns.
result=c()

#Lets say the data file 'data.csv' is stored at location 'D:\dataFolder\data.csv'. Read this file in R.
# Also note the double slash used in file path.
data=data.frame(fread('D:\\dataFolder\\data.csv'))  

#Calculate mean for each column.
for(i in 1:length(colVector)){
     # Fetch current column and calculate its mean.
     colMean=mean(data[,i])
     result=c(result,mean)
}













4. Main.java: This is the starting point of the program. In this file user will define the columns for which mean is to computed. After getting back the results from 'test.R' this class will display the result back to the console.
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); 
// Define the index of columns for which mean is to be calculated (in R index starts at 1, unlike Java where it starts at 0)
//Let's say we need to compute mean for column 1 and column 3. For that we need to construct a R vector in form of Java String.
String columns="c(1,3)";

// All the inputs that are to be supplied to R script, must be supplied to the context before we execute the actual R file having analytics logic.
// For that we have already create 'config.R'. So firstly we will call 'config.R', pass the value of columns and then call actual 'test.R'
// Let's say 'test.R' and 'config.R' are saved directly on D:\ drive.
// Also node four slashes used in the file path.
re.eval("D:\\\\config.R");

//After we have called 'config.R', we have variable 'colVector' available. Now let's populate 'colVector' with user defined column indicies.
re.eval("colVector="+columns);

//Now call the file 'test.R' that will compute the mean of selected columns.
re.eval("D:\\\\test.R");

//Now we have supplied column indicies to R script and R script 'temp.R' will store final means in vector 'result'.
//We will get back result from R and display it in Java.
double[] resultMean=re.eval("result").asDoubles();

//Print results.
for(double mean: resultMean){
  System.out.println(mean);
}

}
}

I hope this will help in creating apps that need to pass data between Java and R & vice-versa.
Thanks

Comments

  1. All your Effective Works Gives These Kind Of Valuable Information's...Thanks for Spending your Good Time.This Unique Information's about Python is very useful
    python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery

    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

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

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