We
will use Rserve software to connect our Java code to R environment. Rserve is a
TCP/IP server which allows other programs to use facilities of R from various languages without the need to
initialize R or link against R library. Every connection has a separate
workspace and working directory. For more details please refer this page https://www.rforge.net/Rserve/
- Install R software in your computer somewhere. (My case it is D:\InstalledSoftware\R-3.4.3)
- Start your R environment
- Install Rserve package (use command install.packages("Rserve"))
- Start Rserve in your R environment (use command library(Rserve))
- That’s it from R side.
- Now setup your Java project.
- Open any Eclipse, create java project say "RJavaConnect"
- Add two Rserve related jar file in your RJavaConnect project (REngine.jar and Rserve.jar)
- You can get both jar from D:\InstalledSoftware\R-3.4.3\library\Rserve\java (In your case check your R installation path). Else you can add these two dependency in your pom.xml
Finally, create one Java Class say
Demo.java and execute below code. That’s it :)
package pkg;
import
org.rosuda.REngine.REXP;
import
org.rosuda.REngine.REXPMismatchException;
import
org.rosuda.REngine.REngineException;
import
org.rosuda.REngine.Rserve.RConnection;
import
org.rosuda.REngine.Rserve.RserveException;
public class Demo {
RConnection
connection = null;
public
static void main(String[] args) {
Demo
demo = new Demo();
demo.connectToR();
}
public
void connectToR(){
try{
connection
= new RConnection();
String
vector = "c(1,2,3,4)";
connection.eval("meanVal=mean(" + vector + ")");
double mean =
connection.eval("meanVal").asDouble();
System.out.println("The mean
of given vector is=" + mean);
/*
String setwd =
"setwd(\"d:/InstalledSoftware/RStudio\")";
connection.eval(setwd);
vector =
"binod<-c p="">-c>
connection.eval(vector);*/
int[] input = {10,20,30,40,50};
connection.assign("input", input);
REXP output =
connection.eval("mean(input)");
System.out.println("Mean of
out input data :"+output);
System.out.println("Mean of
out input data :"+output.asDouble());
}catch
(RserveException e) {
e.printStackTrace();
}catch (REXPMismatchException e) {
e.printStackTrace();
} catch (REngineException e) {
e.printStackTrace();
}finally{
if(connection
!= null){
connection.close();
}
}
}
}
No comments:
Post a Comment
You can put your comments here (Either feedback or your Question related to blog)