RServe Java example program
[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.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Setup
The steps to install and start RServe are shown in the previous tutorial. This tutorial explains how to create a java program that can talk to R using RServe on a linux platform. The steps to set up are.
- Lets assume for this tutorial that the working directory in linux where you want to setup the program is HOME/RServe. Create a directory inside it called lib. The path of lib then is HOME/RServe/lib
- When you install RServe the process downloads the RServe tar and puts its in a directory that you specify. If you dont know where the RServe tar is download it again from here. untar the file using ‘tar -xvf RServe_x.tar.gz‘. Copy REngine.jar and RServe.jar from Rserve_x/clients/java-new to HOME/RServe/lib. Your working directory is now ready to run RServe java programs.
Example Program
Here’s a sample program, that gets the R version using RServe. Its a very basic program but the idea is to get RServe and Java integration up and running for more serious stuff that we will look at later
import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPMismatchException; import org.rosuda.REngine.Rserve.RConnection; import org.rosuda.REngine.Rserve.RserveException; public class RServeExample1 { public static void main(String[] args) throws RserveException, REXPMismatchException { RConnection c = new RConnection(); REXP x = c.eval("R.version.string"); System.out.println(x.asString()); } }
Create a file named RServeExample1.java and copy the code above. Put the file in HOME/RServe. Compile the code using
javac -cp .:lib/* RServeExample1.java
Start RServe as described in the
previous
tutorial.
Run the class using
java -cp .:lib/* RServeExample1
The post RServe Java example program 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.