Calling R Script from Java

calling R script from java

You just want to call an external application: wouldn't the following work?

Runtime.getRuntime().exec("Rscript myScript.R"); 

How do you run an R program from Java?

You might want to take a look at these three projects.

  • JRI - Java/R Interface

  • Rserve

  • RCaller

Run R script using JAVA program

You just want to call an external application: wouldn't the following work?

Runtime.getRuntime().exec("Rscript myScript.R"); 

Credit goes to stackoverflow itself

not able to execute R script from java program?

You will have to run /usr/bin/Rscript directly. Also, this program doesn't read scripts from the standard input (you have to specify the path to the script as an argument for Rscript), so you will have to:

  • Create a temp file
  • Write your script
  • Execute your script with Rscript
  • Delete your temp file (as a good programming practice)

As an example, this is a POC:

public static void main(String[] args) throws IOException, InterruptedException {

// Your script
String script = "#!/usr/bin/env Rscript\n" +
"\n" +
"sayHello <- function() {\n" +
" print('hello')\n" +
"}\n" +
"\n" +
"sayHello()\n";

// create a temp file and write your script to it
File tempScript = File.createTempFile("test_r_scripts_", "");
try(OutputStream output = new FileOutputStream(tempScript)) {
output.write(script.getBytes());
}

// build the process object and start it
List<String> commandList = new ArrayList<>();
commandList.add("/usr/bin/Rscript");
commandList.add(tempScript.getAbsolutePath());
ProcessBuilder builder = new ProcessBuilder(commandList);
builder.redirectErrorStream(true);
Process shell = builder.start();

// read the output and show it
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(shell.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}

// wait for the process to finish
int exitCode = shell.waitFor();

// delete your temp file
tempScript.delete();

// check the exit code (exit code = 0 usually means "executed ok")
System.out.println("EXIT CODE: " + exitCode);
}

As an alternative, and if your script has a "shebang" as the first line, you could do these changes:

  • set its executable attribute to "true"
  • use the path to the temp file as first element in the commandList (i. e. delete commandList.add("/usr/bin/Rscript");)

the part of the code to be modified would be:

...

// create a temp file and write your script to it
File tempScript = File.createTempFile("test_r_scripts_", "");
tempScript.setExecutable(true);
try(OutputStream output = new FileOutputStream(tempScript)) {
output.write(script.getBytes());
}

// build the process object and start it
List<String> commandList = new ArrayList<>();
commandList.add(tempScript.getAbsolutePath());
ProcessBuilder builder = new ProcessBuilder(commandList);

...


Related Topics



Leave a reply



Submit