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