Search code examples
rjavajri

rJava JRI Error R is already initialized (R Call java(new Rengine in Java ))


I could call R from Java and call Java function from R successfully both. However, when I'm trying to use rJava JRI to call Java from R, and Java code instance new REngine. It failed reports R is already initialized and then quit R directly.

My class:

public class testRJava {
    public void testOK(){
        System.out.println("test this funciton could be called OK");
    }
    public void callSample(){
        Rengine re = Rengine.getMainEngine();
        if(re == null){
            re=new Rengine (new String [] {"--vanilla"}, false, null);
            if (!re.waitForR())
            {
                System.out.println ("Cannot load R");
                return;
            }
        }
        // print a random number from uniform distribution
        System.out.println (re.eval ("runif(100)").asDouble());
        re.end();
    }
}

then, I call the Jar from R

> b <- .jnew("testRJava")
> b$testOK()
test this funciton could be called OK
> b$
b$callSample()  b$main(         b$wait()        b$toString()    b$getClass()    b$notifyAll()
b$testOK()      b$wait(         b$equals(       b$hashCode()    b$notify()
> b$callSample()
R is already initialized
[root@ home]#

Any one know why? Any solution about this error ?


Solution

  • library(rJava)

    .jinit(".")

    .jengine(TRUE)

    [1] "Java-Object{Thread[Thread-0,5,main]}"

    b <- .jnew("testRJava")

    b$callSample()