Saturday, March 14, 2015

Handling all variables in a workspace in R with RCaller

It is known that the R assigns a value to a variable name by using the Assignment Symbol <- which corresponds to assign function.

RCaller handles results as list objects. Since R environments are list s, they can easily be converted to R lists (Visit the previous blog post on R list here).

Here is an example of RCaller on getting all variables that are created in the run time in R side.





package rcallerenvironments;

import rcaller.RCaller;
import rcaller.RCode;

public class RCallerEnvironments {

    public static void main(String[] args) {
        RCaller rcaller = new RCaller();
        RCode code = new RCode();
        rcaller.setRscriptExecutable("/usr/bin/Rscript");

        code.addRCode("a <- 3");
        code.addRCode("b <- 10.45");
        code.addRCode("d <- TRUE");
        code.addRCode("avector <- c(9,6,5,6)");
        code.addRCode("allvars <- as.list(globalenv())");

        rcaller.setRCode(code);

        rcaller.runAndReturnResult("allvars");

        System.out.println(rcaller.getParser().getNames());
        try {
            System.out.println(rcaller.getParser().getXMLFileAsString());
        } catch (Exception e) {
            System.out.println("Error in accessing XML");
        }
    }

}

The output is 



As it is seen in output, created variables avector, a, b and d are returned to Java side in a single call without any manual translations.

Have a nice read!


2 comments:

  1. Hi, if you have time, please shed some light on my difficulty with RCaller: https://stackoverflow.com/questions/30318124/rcaller-not-giving-back-variables

    thx

    ReplyDelete
    Replies
    1. Please check the page
      http://stackoverflow.com/questions/30318124/rcaller-not-giving-back-variables/30336169#30336169

      for the answer.

      The example is also available at the github

      https://github.com/jbytecode/rcaller/blob/bb8200f615e9bb50bb405ac199c937167070b7bd/RCaller/src/test/java/org/expr/rcaller/HandlingAllVariablesTest.java

      Delete

Thanks