javarrjavajri

R JRI: trying to create data.frames from Java using REXP.createDataFrame


I'm trying to create a data frame in R taking the data from an ArrayList in Java.

The code below seems to be the official JRI test suite (see this link) however it doesn't even compile, for example in the first statement RList doesn't have a put method and REXP.createDataFrame method doesn't exist.

Is there any updated example of REXP.createDataFrame? Couldn't find a concrete/functional example online. Also, couldn't find any JRI documentation.

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

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

     RList l = new RList();
     l.put("a",new REXPInteger(new int[] { 0,1,2,3}));
     l.put("b",new REXPDouble(new double[] { 0.5,1.2,2.3,3.0}));

     re.assign("z", REXP.createDataFrame(l));

     REXP x = re.parseAndEval("z");
     System.out.println("  z = " + x);

UPDATE

I found out that there are two REXP classes org.rosuda.JRI.REXP and org.rosuda.REngine.REXP, the latter has the method createDataFrame(l), however the assignment doesn't work. How to assing a data frame to an R variable?


Solution

  • If it helps: my solution to create a data frame with JRI-REngine gives some thing like this:

        String[] dummyArgs = {"--vanilla"};
        REngine eng = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine", dummyArgs, new REngineStdOutput (), false); // debug mode, print R-trace in Java
    
        String[] colNames = {"col1", "col2", "col3"};
        String[] col1 = {"a1", "a2", "a3", "a4"};
        String[] col2 = {"b1", "b2", "b3", "b4"};
        int[] col3 = {1, 2, 3, 4};
    
        REXP mydf = REXP
                    .createDataFrame(new RList(
                            new REXP[] {
                                    new REXPString(col1),
                                    new REXPString(col2),
                                    new REXPInteger(col3)},
                            colNames));
    
        eng.assign("myDataFrame", mydf);
    
        eng.parseAndEval("print(myDataFrame)");
    

    In eclipse console :

    col1 col2 col3 1 a1 b1 1 2 a2 b2 2 3 a3 b3 3 4 a4 b4 4