Here are some more detailed instructions for creating an RServe project from scratch:
First Install and get Rserve running in R.
- Install R
- Add package RServe from CRAN.
- In R type: install.packages("Rserve")
For remote access:
- Create file: /etc/Rserv.conf
Add the following to Rserv.conf
workdir /tmp/Rserv
remote enable
auth required
plaintext disable
port 6311
maxsendbuf 0 (size in kB, 0 means unlimited use)
In R: run the following commands
library(Rserve)
For Windows:
Rserve()
For Mac:
Rserve(args="--no-save")
An instance of Rserve is now running on localhost port 6311.
Next Create an Rserve project (i'm using eclipse)
For this I'm going to use eclipse:
- Download RserveEngine.jar and REngine.jar from here.
- Create a java project in eclipse.
- Create a lib folder under your project directory. (same level as your src folder)
- Copy RserveEngine.jar and REngine.jar into the lib folder.
- Add jars to build path: Instructions
- Add a package then a main class: call it something like HelloWorldApp.
Add this code to the class
package com.sti.ai;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class HelloWorldApp {
public static void main(String[] args) throws RserveException, REXPMismatchException, FileNotFoundException, IOException {
RConnection c = new RConnection("<host/ip>", 6311);
if(c.isConnected()) {
System.out.println("Connected to RServe.");
if(c.needLogin()) {
System.out.println("Providing Login");
c.login("username", "password");
}
REXP x;
System.out.println("Reading script...");
File file = new File("<file location>");
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
System.out.println(line);
x = c.eval(line); // evaluates line in R
System.out.println(x); // prints result
}
}
} else {
System.out.println("Rserve could not connect");
}
c.close();
System.out.println("Session Closed");
}
}
Finally, run HelloWorldApp.java
For those who are using Maven
REngine
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>REngine</artifactId>
<version>1.7-3</version>
</dependency>
RServe
<dependency>
<groupId>org.rosuda.REngine</groupId>
<artifactId>Rserve</artifactId>
<version>1.8.1</version>
</dependency>