Search code examples
javarrcaller

Java and R bridge


I want to run r-script from java. I have the following code, but giving null:

try {
    RCaller caller = new RCaller();
    caller.setRscriptExecutable("C:/Program Files/R/R-3.0.1/bin/x64/Rscript.exe");
    caller.cleanRCode();              
    caller.addRCode("k<-1");    //Initializing k to 1
    caller.addRCode("b<-print(k)"); 
    caller.runAndReturnResult("b"); //This should output the value of b      
} catch(Exception e) {
    e.printStackTrace();
}

I don't know what I'm doing wrong. Please help out.


Solution

  • I suggest you download the latest version, 2.1.1. The code below works as expected (prints 1) with version 2.1.1.

    import rcaller.RCaller;
    import rcaller.RCode;
    
    public class RCallerDemo {
        public static void main(String[] args) {
            try {
                RCaller caller = new RCaller();
                caller.setRscriptExecutable("/usr/bin/Rscript");
                caller.cleanRCode();
                RCode code = new RCode();
                final String st1 = "k<-1";
                final String st2 = "b<-print(k)";
                code.addRCode(st1);
                code.addRCode(st2);
                caller.setRCode(code);    //Initializing k to 1
                caller.runAndReturnResult("b"); //This should output the value of b
                int b = caller.getParser().getAsIntArray("b")[0];
                System.out.println(b);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    The example is based on the original RCaller examples.