Reputation: 392
I have an Rscript myrscript.R , which is having below code.
if(exists("e")==FALSE)
{
e = new.env()
}
myfun1<-function(file_path)
{
mydata<-read.csv(file_path)
e$mydata1 =mydata
return("firstfunction")
}
myfun2<-function()
{
e$mydata1
names_mydata<-colnames(e$mydata1)
nm<-names_mydata[1]
return(nm)
}
I am calling this script from java using the following code.
public class mymainclass {
public static void main(String[] args) throws RserveException, REXPMismatchException {
String file_path1="/home/jayshree/test_data.csv";
mymainclass mm=new mymainclass();
String s = mm.myfun_2(file_path1);
String l3 = mm.myfun_3();
System.out.println(s);
System.out.println(l3);
}
public static String myfun_2(String file_path) throws RserveException, REXPMismatchException
{
RConnection c = new RConnection();
c.eval("source(\"/home/jayshree/myrscript.R\")");
c.assign("file_path",file_path);
String a = c.eval("myfun1(file_path)").asString();
return(a);
}
public static String myfun_3() throws RserveException, REXPMismatchException
{
RConnection c = new RConnection();
c.eval("source(\"/home/jayshree/myrscript.R\")");
String b = c.eval("myfun2()").asString;
return(b);
}
}
While running this from java. It throwing mismatch error. The error is coming because, while calling the second function of the R script.The value of global variable e$mydata1 is not getting initialized, and is null. But it should not. I ran the code of the script file in R console. It is running fine . But while calling from java, why the global variable thing is not working. Is there any alternative solution.
Upvotes: 0
Views: 635
Reputation: 13932
You're creating a new connection each time, so the calls are entirely independent. I.e, in myfun_3
you start an empty, new R session so it is expected that it won't have any data loaded. If you want the functions to work on the same session, you have to use the same RConnection
object.
Upvotes: 2