RServe Java Source R script

[This article was first published on R – StudyTrails, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

The post RServe Java Source R script appeared first on StudyTrails.

To leave a comment for the author, please follow the link and comment on their blog: R – StudyTrails.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)