1

I have installed JRI to run with NetBeans 7.4 using 32-bit R 3.0.2 and Java jdk1.7.0_45, on Windows 7.

I am using the following Java function.

import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.RList;

void testJRI(){

    // Start JRI engine. 
    String[] Rargs = {"--vanilla"};
    Rengine re = new Rengine(Rargs, false, null);

    if (!re.waitForR()) {
        System.out.println("Cannot load R");
        return null;
    }

    REXP load=re.eval("source('C:\\\\searchPath\\\\nonparametricAnova.r')");
    re.end();

    return;
}

The first time the function is called, everything works fine. But the second time, the variable, load, is null - indicating failure.

I replaced the nonparametricAnova.r R function with the following simple script

simple<-function(){
  a=1
  a
}

which I named simple.r and called with

    REXP load=re.eval("source('C:\\\\searchPath\\\\simple.r')");

Now, the second time through, it hangs on

Rengine re = new Rengine(Rargs, false, null);

I have noticed that

load=re.eval("refClusterMeasurements<-read.csv(\"C:/SearchPath/fileName.csv\", header=TRUE)");

also fails the second time through, even if "name.csv" is a minimally sized file.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
OtagoHarbour
  • 3,969
  • 6
  • 43
  • 81

1 Answers1

1

This version works:

package stackoverflow;

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

/**
 *
 * @author yschellekens
 */
public class StackOverflow {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {




 // Start JRI engine. 
    String[] Rargs = {"--vanilla"};
    Rengine re = new Rengine(Rargs, false, null);

      re.eval("source('C:/Users/yschellekens.INTRANET/Desktop/java projects/simple.R')");
       REXP value =re.eval("as.integer(a<-simple())");
   int a  = value.asInt();
        System.out.println(a);


    }
} 

using the following R file:

simple<-function(){
  a=1
  return(a)
}

Java output:

run:
1

Notice several differences:

  1. Don't use REXP load= before the re.eval("source...
  2. Save your r file with .R
  3. Change your dashes to : /

This code work's fine many times, please let me know if that solved the issue.

Yehoshaphat Schellekens
  • 2,305
  • 2
  • 22
  • 49
  • It was still hanging after using the above code. Then I added re.end(); just before return and it solved the hanging issue. – Rana Oct 13 '16 at 08:40
  • when I am using it as a web service, the first call made returns response but for the second time onwards it got hanged eating memory and CPU. – Rana Oct 13 '16 at 11:37
  • I got the solution at [here](http://stackoverflow.com/questions/39994141/calling-r-script-function-from-java-using-rjava/40104285#40104285) – Rana Oct 18 '16 at 09:22