REXP as List does not return the output

403 views Asked by At

I have a java code and I'm using Rserve to run my R code inside the java. Here is a part of my code:

RConnection c = new RConnection("localhost", 6311);
c.eval("library(e1071)");
c.eval("data(HouseVotes84, package = 'mlbench')";
c.eval("model <- naiveBayes(Class ~ ., data = HouseVotes84)")
REXP t = c.eval("NBC <- model$tables");
List<Double> NBCList = new ArrayList<Double>();
t.asList().add(NBCList);
System.out.println(NBCList);

The problem is that it returns the following:

[]

and the correct output (not using Rserve - directly running on R session) should be:

$V1
        V1
Y                    n         y
  democrat   0.3953488 0.6046512
  republican 0.8121212 0.1878788

$V2
        V2
Y                    n         y
  democrat   0.4979079 0.5020921
  republican 0.4932432 0.5067568
1

There are 1 answers

0
Yehoshaphat Schellekens On BEST ANSWER

Notice that you have some typos there, please check it in your IDE, also you are not passing correctly data from R to Java.

See the following code of how to use it, this code only passes the

NBC$V1[1]

Element of NBC into Java, you'll have to do a lot of Work to pass stuff to java, since R has different types that Java.

See the following Example, notice that i also inserted code that tells you if libraries are correctly installed for Java To use:

import java.io.File;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;


public class RunDavid {


public static void main (String args []) {


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

 System.out.println("R_HOME =" + System.getenv("R_HOME"));
  String path =System.getenv("R_HOME") + "\\library" ;
   File folder = new File(path);
  File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
      }
    }

re.eval("library(e1071)");
re.eval("data(HouseVotes84, package = 'mlbench'))");
re.eval("model <- naiveBayes(Class ~ ., data = HouseVotes84)");
re.eval("NBC <- model$tables");
REXP  t = re.eval("NBC$V1[1]");
System.out.println(t.asDouble());
}}

Please let me know if that works for you :)