Search code examples
javarrjavajri

JRI, Java and R: variable is not accumulated between evals


In this code variable xx returns 0 instead of 20, shouldn't it be calculated and its value kept between evals?

     String[] Rargs = {"--vanilla"};
     Rengine re = new Rengine(Rargs, false, null);

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

     re.eval("xx = 0");
     for (int i=0; i<20; i++) {
         re.eval("xx =  xx + 1");
     }

     int xx = (re.eval("xx")).asInt();
     System.out.println("xx="+xx);

This is the result:

xx=0

Solution

  • This is the answer, need to use asDouble():

    double xx = (re.eval("xx")).asDouble();