Search code examples
javaeclipserrserve

Simple program to call R from Java using Eclipse and Rserve


My application must perform R operations such as:

m = matrix(sample(0:1,100, rep=T),ncol=10)

The results should be available to a Java application.

The Rserve package bridges R to other languages, since it acts as a TCP/IP server. I've read the website but don't know how to make the simplest application that can use Rserve.

What steps are required to make a simple Eclipse application that uses Rserve to execute R commands from Java?


Solution

  • There is a binary version of Rserve in the download section (www.rforge.net/Rserve/files/ I have version R 2.13 and Windows xp, so I need download Windows binary: Rserve_0.6-8.zip (541.3kb, updated: Wed Apr 18 07:00:45 2012)). Copy the file to the directory containing R.DLL. After installed Rserve from CRAN

    install.packages("Rserve")
    

    in R (I have RStudio - convenient thing: Download RStudio IDE). started Rserve is from within R, just type

    library(Rserve)
    Rserve()
    

    Сheck in Task Manager - Rserve.exe should be run. After make a Java project in Eclipse, make a directory called lib under that project. Paste 2 jar here RserveEngine.jar and REngine.jar (www.rforge.net/Rserve/files/). Do not forget to add this jars in Properties your java-project. In new class code:

    import org.rosuda.REngine.*;
    import org.rosuda.REngine.Rserve.*;
    
    public class rserveuseClass {
        public static void main(String[] args) throws RserveException {
            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");
                System.out.println(x0.asString());
    } catch (REngineException e) {
                //manipulation
            }       
    
        }
    }