Search code examples
javarrserve

Running rscript from java doesnt show any result


I am using Rserve to call r script from java. The program runs and terminates but doesn't output what i want. In my R script i have multiple print statement so in theory when my java program runs it should print those statement. But my java program is printing the path of my rscript not the actual r script content.

what should i do?How do i know if my script is running correctly?

R script:

library(Rserve)
Rserve()
print(323325)
print("Hellow world this is an R script")
print("R script ran successfully")
print("Running")

Java program:

public static void main(String[] args) throws REXPMismatchException, REngineException{

        RConnection c = new RConnection();
        //REXP rengine = c.eval("R.version.string");
        //rengine = c.eval("source('./src/main/resources/Script/DB.R')");
        //System.out.println(rengine.asString());



        REXP rResponseObject = c.parseAndEval("try(eval('./src/main/resources/Script/DB.R'),silent=TRUE)");
        System.out.println(rResponseObject.asString());
        if (rResponseObject.inherits("try-error")) { 
            System.err.println("Error: " + rResponseObject.asString());
        }


    }

Actual output:

./src/main/resources/Script/DB.R

Desired output:

[1] "Hellow world this is an R script" [1] "R script ran successfully" [1] "Running"


Solution

  • I solved the problem. My r script is now running correctly and performing the action it is supposed to.

    In my r script file, I created a function and put my entire r code within that function

    In my java program, i gave path of my r script like this:

    c.eval("source(\"DataPull.R\")");
    

    Then i called the function of my r script and checked for errors like this:

    REXP r = c.parseAndEval("try(eval(myAdd()),silent=TRUE)");
            if (r.inherits("try-error")) System.err.println("Error: "+r.asString());
                else System.out.println("Success eval 2");
    

    and it worked.

    Here is my java program file:

    public static void main(String[] args) throws REXPMismatchException, REngineException, IOException{
    
            RConnection c = new RConnection();
            c.eval("source(\"DataPull.R\")");
            REXP r = c.parseAndEval("try(eval(myAdd()),silent=TRUE)");
            if (r.inherits("try-error")) System.err.println("Error: "+r.asString());
                else System.out.println("Success eval 2");  
        }
    

    here is my r script file:

    myAdd <- function(){
      library(Rserve)
      Rserve()
      print(323325)
      print("Hellow world this is an R script")
      print("R script ran successfully")
      print("Running")   
    }