Executing R Script from Java

35 Views Asked by At

I am trying to execute an R Script using java program. But json file which has to be generated in the script is not getting generated. But if i run the same r script in R, json file is getting generated.

Below is the java program

package com.demo;

import org.rosuda.JRI.Rengine;

public class R {

    public static void main(String[] args) {
        System.out.println("Start");
        Rengine r = new Rengine(new String[] {"--vanilla"}, false, null);
        r.eval("source(\"/home/ubuntu20/Documents/RProjectCheck/Sample.r\")");
        System.out.println("Done");
    }
    
}

Below is the R Script which is stored in a file Sample.r

attach(iris)

c5func<-function()
{

    myTryCatch <- function(expr) {
    warn <- err <- NULL
    value <- withCallingHandlers(
    tryCatch(expr, error=function(e) {
    err <<- e
     NULL
    }), warning=function(w) {
    warn <<- w
    invokeRestart("muffleWarning")
    })
    list(value=value, warning=warn, error=err)
    }
    
    depvar<-"Species"
    model<-C50::C5.0(Species ~ Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, data=iris ,trials=1, rules=TRUE, 
    control=C50::C5.0Control(subset=FALSE, winnow=FALSE, noGlobalPruning=TRUE, CF=0.25, minCases=2))
    model
    library(caret)
    confmatcode<-paste("confusionMatrix(predict(model, type='class', iris),",depvar,")",collapse="", sep="")
    
    if(is.null(myTryCatch(eval(parse(text=confmatcode)))$error))
    {
        confmattrain<-eval(parse(text=confmatcode))
        write(jsonlite::serializeJSON(confmattrain), file="/home/ubuntu20/Documents/RProjectCheck/GeneratedFiles/ConfusionMatrix.json")
    }
}

c5func()
rm(list=ls())
gc()

The environment which has been used is R Version 4.2.3 and Ubuntu 20.04.6

1

There are 1 best solutions below

1
br00t On

On Ubuntu you can do the following:

  1. Modify Sample.r so that it can be run as a standalone script

#!/usr/bin/Rscript

c5func<-function()
{

    myTryCatch <- function(expr) {
    warn <- err <- NULL
    value <- withCallingHandlers(
    tryCatch(expr, error=function(e) {
    err <<- e
     NULL
    }), warning=function(w) {
    warn <<- w
    invokeRestart("muffleWarning")
    })
    list(value=value, warning=warn, error=err)
    }
    
    depvar<-"Species"
    model<-C50::C5.0(Species ~ Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, data=iris ,trials=1, rules=TRUE, 
    control=C50::C5.0Control(subset=FALSE, winnow=FALSE, noGlobalPruning=TRUE, CF=0.25, minCases=2))
    model
    library(caret)
    confmatcode<-paste("confusionMatrix(predict(model, type='class', iris),",depvar,")",collapse="", sep="")
    
    if(is.null(myTryCatch(eval(parse(text=confmatcode)))$error))
    {
        confmattrain<-eval(parse(text=confmatcode))
        write(jsonlite::serializeJSON(confmattrain), file="/home/ubuntu20/Documents/RProjectCheck/GeneratedFiles/ConfusionMatrix.json")
    }
}

c5func()
rm(list=ls())
gc()
  1. Make your script file executable

chomd u+x Sample.r

  1. Modify your java class so that it launches your R script as a shell process
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellCommand {

        public static void main(String[] args) {
                ExecuteShellCommand obj = new ExecuteShellCommand();
                String output = obj.executeCommand("./Sample.r");
                System.out.println(output);
        }

        private String executeCommand(String command) {
                StringBuffer output = new StringBuffer();
                Process p;
                try {
                        p = Runtime.getRuntime().exec(command);
                        p.waitFor();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = "";
                        while ((line = reader.readLine())!= null) {
                                output.append(line + "\n");
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                }
                return output.toString();
        }
}