Running rscript from java shows no result

I am using Rserve to call r script from java. The program starts and exits, but doesn't output what I want. In my R script, I have a multiple print statement, so in theory, when my java program starts, it should print that statement. But my java program prints the path of my rscript, not the actual content of the r script.

what should I do? How do I know if my script is working 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/ core/ resources/Script/DB.R

Desired output:

[1] "Hellow world this is an R script" [1] "R script runs successfully" [1] "Run"

+3


source to share


2 answers


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

In my r script file I created a function and put all my r code in this function

In my java program, I gave the path to 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")   
}

      

0


source


eval

evaluates the expression. './src/main/resources/Script/DB.R'

is a constant string that evaluates itself.



You probably need source

.

0


source







All Articles