简体   繁体   中英

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.

From the "Program Files" path, I'll get you're working on Windows. If so, there is a chance that your problem are the slashes on the path:

caller.setRscriptExecutable("C:/Program Files/R/R-3.0.1/bin/x64/Rscript.exe");

Try this instead:

caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.0.1\\bin\\x64\\Rscript.exe");

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM