This is my sample R file :
# filename: sample.R
main <- function (){
returnStringValue <- "ignore"
return (returnStringValue)
}
main()
Now I am trying to source on the file on Rserve using java:
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
public class RServeTest {
static RConnection rcon;
public static void main(String[] args) {
try {
String fileName = "sample.R";
String filePath = "/filepath/";
try {
rcon = new RConnection();
}
catch(Exception e){
System.out.println("Error Connecting: "+e);
}
String rCode = "source(\""+filePath+fileName+"\")";
System.out.println("Rscript call on file: "+rCode);
REXP r = rcon.parseAndEval("try(eval(parse(text="+rCode+")),silent=TRUE)");
System.out.println("r object: "+r.asString());
if (r.inherits("try-error"))
System.err.println("Error: "+r.asString());
else
System.out.println("Executed R code successfully.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
which gives me the following error:
Rscript call on file: source("/home/maverick/Documents/sem3/agent code/sample.R")
Error: Error in eval(expr, envir, enclos) : object 'ignore' not found
How do I handle string values getting returned from the R code, without affecting the errors getting caught?
For eg:
Let's say I have a bug in my code:
main <- function (){
returnStringValue <- "ignore"
# error
var1+1
return (returnStringValue)
}
main()
The java code should log :
Rscript call on file: source("/filepath/sample.R")
Error: Error in main() : object 'var1' not found
rather than logging :
org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:233)
at RServeTest.main(RServeTest.java:39)