From QERM Wiki
Revision as of 23:22, 9 September 2013 by Chloe (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

How to call R from a Java program


Using JRI (from RJava)

The RJava package also allows calling Java from R.

Set up

  • In R, install the RJava package (necessary?)
  • The RJava package includes the JRI.jar, but to get JRIEngine.jar and REngine.jar, go to JRI files download
  • Add those 3 jars to your lib directory and classpath
  • Make sure the R_HOME environment variable is set
    • Type $R_HOME on the command line to see if it is set and what it is set to
    • In eclipse, you can add environment variables to the run configuration
    • On a mac, add this line to your .profile file (in the root of your user directory, so ~/.profile)
export R_HOME=/Library/Frameworks/R.framework/Resources
  • Add the native JRI library to the Java library path (either on the command line call to Java or as a VM argument in the eclipse run configuration)

Calling R

Here is a very short example. See the links below and the example directory for more.

public void demoCallR() throws Exception
  REngine re = null;
    re = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine");

    re.assign("num", new int[] { 1 });
    REXP result = re.parseAndEval("num + 1");
     if (re != null)

Which API to use

Confusingly, there are several API's to use. The recommended one is the high-level org.rosuda.REngine API.

REngine eng = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine");  
eng.assign("x", "Peter")

See mailing list posts here and here. Note that this is different than many of the examples in the links below, which all show something like this:

// Start R 
Rengine re = new Rengine(new String[] { "--no-save" }, false, null); //specify '--save', '--no-save' or '--vanilla'

if (!re.waitForR())
  System.out.println("Cannot load R");
  // print a random number from uniform distribution
  System.out.println(re.eval("runif(1)").asDouble ());
   // close R

Helpful links

Other solutions

  • renjin this looks promising, a JVM-based interpreter for R, but still beta
  • Rserve more complicated client/server setup, so more useful for lots of processes needing R
  • Rcaller very simple, but looks clunky for doing anything more than a few lines in R
Personal tools