简体   繁体   中英

Executing R file from bash script

I need to run the same R script over and over with different parameters for each run. I've written the R portion and it works. I'm trying to integrate this process with some other Java tools I've written that will need to use on the files changed by the R script. I'm therefore trying to run my R file from Java. I've tried to run it using the command line prompt: RScript TestR.R (this command works in terminal), but that didn't work. I am therefore in the process of trying to run my R script from a bash file. I am using the same command as above and my bash file can execute other commands but for some reason nothing happens when I try to run the R file. The java command I'm using is

Process proc = Runtime.getRuntime().exec("absolute-path/testbash.sh");

I'm not sure what format of output to look for. Currently, this runs without any runtime errors.

UPDATE: when I checked the ErrorStream, it said "Rscript: command not found"

UPDATE: I figured it out by using "/usr/local/bin/RScript" as the command

您可以通过以下方式进行操作:

new ProcessBuilder("<absolute-path-to-script>/testbash.sh").start();

With simple R code I have found it easier to call RScript from the terminal, within Java, and parse the output of the R code. If you print whatever information you want in an easily parsed format this can work well.

For instance I will call a function like so in Java

private ArrayList<String> runCommand(String command)
{
    try
    {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command);

        BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

        String lastReadLine = null;
        ArrayList<String> output = new ArrayList<>();
        while((lastReadLine = stdInput.readLine()) != null)
            output.add(lastReadLine);
        return output;
    }
    catch(Exception ex) { throw new RuntimeException("[RunCommand]: Exception when trying to execute command: " + ex.getMessage()); }
}

with the argument \\pathTo\\RScript \\pathTo\\MyRCode.R and parse the resulting ArrayList<String> in Java to obtain whatever information the R code produced.

There are other ways to do this to. You could potentially write out some JSON file from the R code and return a path to this in the R code output, Java could then parse and read this file. Or you could use one of the many R-Java interop libraries out there (Just google).

Hope this helped.

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