Monday, 14 May 2012

Call R from Java

We can integrate R with Java or java based application using Rserve.
What is Reserve?
Rserve is a TCP/IP server which allows other programs to use facilities of R (see from various languages without the need to initialize R or link against R library. Every connection has a separate workspace and working directory. Client-side implementations are available for popular languages such as C/C++, PHP and Java. Rserve supports remote connection, authentication and file transfer. Typical use is to integrate R backend for computation of statstical models, plots etc. in other applications.

I am going to show you an example of creating a R graph from Java.

To call R from java you have to download some JAR files . Download these files from

1:- Start Eclipse and create a new java project

2:- Add REngine and RserveEngine.jar JAR files
3:- Add a class file and copy this code to start Rserve and just run that class file

package com.test.CallRfromJava;

import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;

public class callingrserve {

     public static void main(String[] args) throws RserveException, REXPMismatchException {
            try {
                RConnection c = new RConnection();// make a new local connection on default port (6311)
                double d[] = c.eval("rnorm(10)").asDoubles();
                org.rosuda.REngine.REXP x0 = c.eval("R.version.string");
    } catch (REngineException e) {



4:- Add  one more class file and copy this code and run that file, you should get the a R graph

package com.test.CallRfromJava;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;

public class PlotDemo extends Canvas {
    public static void main(String args[]) {
        try {
            String device = "jpeg";
    RConnection c = new RConnection((args.length>0)?args[0]:"");

    if (c.parseAndEval("suppressWarnings(require('Cairo',quietly=TRUE))").asInteger()>0)
            System.out.println("(consider installing Cairo package for better bitmap output)");
           REXP xp = c.parseAndEval("try("+device+"('test.jpg',quality=90))");
         if (xp.inherits("try-error")) {
                System.err.println("Can't open "+device+" graphics device:\n"+xp.asString());
 REXP w = c.eval("if (exists('last.warning') && length(last.warning)>0) names(last.warning)[1] else 0");
                if (w.isString()) System.err.println(w.asString());
    c.parseAndEval("data(iris); attach(iris); plot(Sepal.Length, Petal.Length, col=unclass(Species));");

            xp = c.parseAndEval("r=readBin('test.jpg','raw',1024*1024); unlink('test.jpg'); r");
            Image img = Toolkit.getDefaultToolkit().createImage(xp.asBytes());
            Frame f = new Frame("Test image");
            f.add(new PlotDemo(img));
            f.addWindowListener(new WindowAdapter() {
                // just so we can close the window
                public void windowClosing(WindowEvent e) { System.exit(0); }

            // close RConnection, we're done
        } catch (RserveException rse) {
            // RserveException (transport layer - e.g. Rserve is not running)
        } catch (REXPMismatchException mme) {
            // REXP mismatch exception (we got something we didn't think we get)
        } catch(Exception e) {
            // something else
            System.out.println("Something went wrong, but it's not the Rserve: "
    Image img;

    public PlotDemo(Image img) {
        MediaTracker mediaTracker = new MediaTracker(this);
        mediaTracker.addImage(img, 0);
        try {
        } catch (InterruptedException ie) {
        setSize(img.getWidth(null), img.getHeight(null));
    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);