Executing an R script in a way other than using source() in JRI

1.1k views Asked by At

I am new to R and have been trying to use JRI. Through JRI, I have used the "eval()" function to get certain results. If I want to execute an R script, I have used "source()". However I am now in a situation where I need to execute a script on continuously incoming data. While I can still use "source()", I don't think that would be an optimal way from a performance perspectve.

What I did was to read the entire R script into memory and then try and use "eval()" passing the script - but this does not seem to work. I have ensured that the script has been correctly loaded into memory - that is because if I write this script (loaded into the memory) into a file and source this newly created file, it does produce the expected results.

Is there a way for me to not keep sourcing the same file over and over again and execute it from memory? Each of my data units are independent and have to be processed independently and as soon as they become available. I cannot wait to collect a bunch of data units and then pass them on to the R script.

I have searched a lot and not found anything related to this. Any pointers which could help me in this direction would be really helpful.

1

There are 1 answers

0
user2940063 On

The way I handled this is as below -

  1. I enclosed the entire script into a function.
  2. I sourced the script file (which now contains the function) at the start of the execution of my program.
  3. The place where I was sourcing the file, I am now just calling the function which contains the script itself i.e. -

    REXP result = rengine.eval("retVal<-" + getFunctionName() + "()");

    Here, getFunctionName() gives me the name of the name of the function which contains the script.

Since this is loaded into the memory and available, I do not have to source the script file every time I want to execute the script. Any arguments being passed to the script are done as env. variables.

This seems to be a workaround, but solves my problem. Any better options are welcome.