Concept
There are two ways to source R script file in RServe Java program. The first way is to directly source it in the java code. The only disadvantage of this method is that each connection would need to do this. As an example consider the following R code
# http://rosettacode.org/wiki/Palindrome_detection#R ############################################################################### palindrome <- function(p) { for(i in 1:floor(nchar(p)/2) ) { r <- nchar(p) - i + 1 if ( substr(p, i, i) != substr(p, r, r) ) return(FALSE) } TRUE }
To source it directly in java
import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPMismatchException; import org.rosuda.REngine.Rserve.RConnection; import org.rosuda.REngine.Rserve.RserveException; public class SourcingRFile { public static void main(String[] args) throws RserveException, REXPMismatchException { RConnection c = new RConnection(); // source the Palindrom function c.eval("source(\"[PATH-TO]Palindrome.R\")"); // call the function. Return true REXP is_aba_palindrome = c.eval("palindrome('aba')"); System.out.println(is_aba_palindrome.asInteger()); // prints 1 => true // call the function. return false REXP is_abc_palindrome = c.eval("palindrome('abc')"); System.out.println(is_abc_palindrome.asInteger()); prints 0 => false } }
Another way to source palindrome.R is via the RServe.conf file. The file is present at /etc/Rserve.conf. If the file is not present then create a new one. Add the following line in the Rserve.conf file
source Palindrome.R
If the default file is not used then specify the file on the command line
R CMD Rserve --RS-conf Rserv.conf
The java code remains same except that line 11 in the code above is deleted.
Hi Mithil,
Its a great example to get started with RServe. I was able to send the commands to be executed on the remote R server, but I wanted to execute a R script present in a remote location itself. Is that possible through Rserve? If yes, how?
Hi,
Thank you for the post. I have sourced the R script in my remote machine’s Rserv.conf file. But when executing I get the error :
org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:261)
on this this line: c.eval(“palindrome(‘aba’)”);
Why is it not reading the function from the sourced script, I’m wondering. FYI I didnt get any error in starting the Rserve with this conf file and the function is present in the script.