calling R script from java

后端 未结 5 1945
梦如初夏
梦如初夏 2020-12-08 05:36

I would like to call an R script from Java. I have done google searches on the topic, but almost all of the results I have seen would require me to add a dependency to some

相关标签:
5条回答
  • 2020-12-08 05:45

    ...would require me to add a dependency to some third party library...

    Why is that so bad? You make it sound like "...would require me to assault a honeybadger with a baseball bat..." I don't see the harm, especially if it works.

    Maybe RCaller can help you. No JNI required.

    0 讨论(0)
  • 2020-12-08 05:54
    BufferedReader reader = null;
            Process shell = null;
            try {
                shell = Runtime.getRuntime().exec(new String[] { "/usr/bin/Rscript", "/media/subin/works/subzworks/RLanguage/config/predict.R" });
    
                reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
    
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    0 讨论(0)
  • 2020-12-08 05:56

    You can easily adapt this code: http://svn.rforge.net/org/trunk/rosuda/REngine/Rserve/test/StartRserve.java

    Among other things it finds R and runs a fixed script in R - you can replace that script with with your script and ignore the last two methods.

    0 讨论(0)
  • 2020-12-08 06:01

    Do not wait for the process to finish with Thread.sleep()...

    Use the waitFor() method instead.

    Process child = Runtime.getRuntime().exec(command, environments, dataDir);
    
    int code = child.waitFor();
    
    switch (code) {
        case 0:
            //normal termination, everything is fine
            break;
        case 1:
            //Read the error stream then
            String message = IOUtils.toString(child.getErrorStream());
            throw new RExecutionException(message);
    }
    
    0 讨论(0)
  • 2020-12-08 06:09

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

    Runtime.getRuntime().exec("Rscript myScript.R"); 
    
    0 讨论(0)
提交回复
热议问题