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
On Ubuntu you can do the following:
chomd u+x Sample.r