tags:

views:

315

answers:

3
+4  Q: 

R from within Java

What's the best way to call R functionality from within Java?

I'm looking for a quick, easy and reliable way to make standard 2d scatter plots and histograms in R using my Java applications. I was wondering which packages/interfaces that came up in a quick Google search would be most convenient to use.

I look forward to your suggestions!

+3  A: 

Use JRI: http://www.rforge.net/JRI/. It comes bundled with rJava, including some examples of usage.

A very simple example would be like this:

import java.io.*;
import java.awt.Frame;
import java.util.Enumeration;

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

public class rJavaTest {

    public static void main(String[] args) {

        Rengine re=new Rengine(args, false, new TextConsole());
        REXP x;
        re.eval("print(1:10/3)");
        System.out.println(x=re.eval("iris"));
        RVector v = x.asVector();
        if (v.getNames()!=null) {
            System.out.println("has names:");
            for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
                System.out.println(e.nextElement());
            }
        }

        if (true) {
            System.out.println("Now the console is yours ... have fun");
            re.startMainLoop();
        } else {
            re.end();
            System.out.println("end");
        }
    }
}
Shane
+2  A: 

I have found that forking R as a process, attaching to the process's stdin, stdout, and stderr streams, and sending R commands via the input stream to be quite effective. I use the filesystem to communicate between R and my Java process. This way, I can have multiple R processes running from different threads in Java and their environments do not conflict with each other.

algoriffic
You can have multiple instances of JRI running in separate threads and there will be no conflict.
Shane
A: 

Thanks for the example !!! Do you Know how can i use it whith an applet ?? i`m working whith Eclipses.

Thankssssssssssss !!!

rcr
For reference: (1) this should be a comment (or a separate question), not an answer, (2) please use correct grammar and spelling, and (3) yes, you can use it from an Applet, and with Eclipse (use the StatET plugin for R). For R web stuff, you may want to look at Rapache instead.
Shane
Sorry, I will try to do it better this time. First of all, thank you for the answer. I have a question about the example : what is "iris"? Thank you.
rcr
iris is an old data set, developed by Fisher, that ships with R and is often used in demonstrations. See: http://en.wikipedia.org/wiki/Data_set#Classic_data_sets
Sharpie