Install R and R packages
Install R from https://cran.r-project.org/bin/windows/base/
Install RStudio from https://www.rstudio.com/products/rstudio/download/ which workspace can be used to develop R programs
Install rJava Package by executing the below command in R command window.
Choose a mirror from the popup window to install rJava. It would be better to select USA (KS)
If it takes too much time, click on stop. Open R studio, and then navigate to Packages tab in right side panel and click on install option.
Type rJava and click on install.
Enter install.packages(‘Rserve’) in R command window. Or else Navigatge to Packages in RStudio and click on install to enter Rserve.
R setup is ready with its packages. We can run R programs in R or in R Studio.
Integrate R With Java using rJava
Right click on My Computer and select Properties.
In the System window that appears, select Advanced system settings.
System Properties dialog will appear, on this dialog select Environment Variables.
Under System variables section search for variable PATH. Select PATH variable and click on Edit button.
Append C:\R\R-3.2.1\bin\i386;C:\R\R-3.2.1\library\rJava\jri\;C:\R\R-3.2.1\library\rJava\jri\i386;
Click ok ok ok.
Create a java project in Eclipse. Say, RJRISamples
Right click on project and select BuildPath à Configure Build Path
Click on Add External Jars in Libraries tab. Select JRI jars from the R installed path.
Run program
/**
*
*/
package com.tms.rundown.r.jri.samples;
import org.rosuda.JRI.Rengine;
/**
* @author 157330
*
*/
public class RMeanStat {
public static void main(String[] args) {
String jVector = "c(1,2,3,4,5)";
Rengine re = new Rengine(new String[] { "--no--save" }, false, null);
re.eval("rVector="+jVector);
re.eval("meanValue=mean(rVector)");
double mean = re.eval("meanValue").asDouble();
System.out.println("Mean: "+mean);
}
}
Output:
Integrate R with Java using rJava along with rJava Eclipse plugin
Download rJava eclipse plugin from https://drive.google.com/file/d/0B9RCRuTCZ_FRbnNZYVBGWlBOdUE/view?pli=1
Copy the jar to eclipse plugins directory. <Eclipse_home>/plugins/
Restart Eclipse
Once the plugin is installed. Click on Eclipse->Preferences->RJava. Select the four directory paths using the browse button. The paths are explained below
"Path to JRI DLL Dir" : This is the directory that contains jri.dll. When you install the rJava package, a folder called 'rjava' is created in the folder that stores all installed libraries in R. if you dont know where that is, open up R and fire the command 'library()'. This will open up another window that shows the path where the libraries are installed. Look for rjava. The line on the top gives the installation path. select the [rjava]/jri folder from the preference page. If your machine is 64 bit select [rjava]/jri/x64
"Path to JRI JARS" : Select the [rjava]/jri folder. Make sure that this folder contains JRI.jar, JRIEngine.jar, REngine.jar. This path is generally same as the one above, unless you want to put the jars in a different location. If any of the above jar is missing then you can download them from http://www.rforge.net/JRI/files/ .
"Path to R DLL Dir" : This specifies the path to R.dll. It should be present in R_Home/bin or R_home/bin/x64 for 64 bit machines.
"Path to JVM DLL dir" : This specifies the path to jvm.dll. It should be present in JRE_HOME/bin/server or JRE_HOME/bin/client.
Click on Apply and then OK. Now you are ready to create your first application.
Create Java application
Create New Java Project.
Right click on the Java project -> select 'Build Path' -> click 'Add Libraries'.
In the popup that comes up, select 'User Library' and click 'Next'.
you should see a library called 'JRI_DIR'. Select it and click Finish. You are now ready to write your first class. (If you don't see the JRI_DIR then simply add the jars from [rjava]/jri/ to your classpath.)
To test immediately, go to [rjava folder]/jri/examples/ and copy rtest2.java into the new project that you have just created. If it compiles correctly then the first phase is complete. Next we run it.
To run a class that contain RJava code. Right click on the class->select 'Run As'->Click on 'Run Configurations'.
In the run configuration window, there should be a run configuration that says 'R'. Select that and click on the 'New Launch Configuration' icon on the top. This will create a new launch configuration. Click on 'Run'. That's it!
Integrate R with java using Rserve:
Follow Rserve installation steps to install Rserve if not installed previously.
Start Rserve as follows from R
Create a sample project in Eclipse using Rserve. Right click on Project select Build Path à Configure Build Path. Add the below jars from Rserve installed packages
If required download and configure RserveEngine.jar
Create code using Rserve and Run.
package com.tms.rundown.r.rserve.samples;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class RMeanSample {
public static void main(String[] args) throws REXPMismatchException {
try {
RConnection connection = new RConnection();
String jVector = "c(1,2,3,4,5)";
connection.eval("meanValue=mean(" +jVector+")");
double mean = connection.eval("meanValue").asDouble();
System.out.println("Mean: "+mean);
connection.close();
} catch (RserveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output:
Call RScript in Java
Create an R sample in RStudio or textpad.
Create Java code and Run
/**
*
*/
package com.tms.rundown.r.rserve.samples;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
/**
* @author 157330
*
*/
public class RScriptSample {
public static void main(String[] args) {
try {
int num1 = 10;
int num2 = 20;
RConnection conn = new RConnection();
conn.eval("source('C:\\\\Rworkspace\\\\RSamples\\\\SumXY.R')");
int sum = conn.eval("addFunc("+num1+", "+num2+")").asInteger();
System.out.println("Sum: "+sum);
conn.close();
} catch (RserveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (REXPMismatchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output:
Integrate R with Java using rCaller
Download rcaller jar from http://code.google.com/p/rcaller/downloads/detail?name=RCaller-2.1.1-SNAPSHOT.jar&can=2&q=
Create a java project.
Add rcaller jar to project classpath.
Create Java code to integrate with R
/**
*
*/
package com.tms.rundown.r.rcaller.samples;
import rcaller.RCaller;
import rcaller.RCode;
/**
* @author 157330
*
*/
public class RCallerSample {
public static void main(String[] args) {
RCaller rc = new RCaller();
rc.setRscriptExecutable("C:\\R\\R-3.2.1\\bin\\RScript.exe");
double[][] matrix = new double[][]{{6, 4}, {9, 8}};
RCode code = new RCode();
// Passing Java objects to R
code.addDoubleMatrix("x", matrix);
code.addRCode("s <- solve(x)");
rc.setRCode(code);
// Performing Calculations
rc.runAndReturnResult("s");
// Passing R object to Java
double[][] inverse = rc.getParser().getAsDoubleMatrix("s", 2, 2);
System.out.println("Inverse: "+inverse);
}
}
Output: Runtime error.
Integrate R with java using Rengin
Download renjin-script-engine-0.7.0-RC7.jar from http://nexus.bedatadriven.com/content/groups/public/org/renjin/renjin-script-engine/0.7.0-RC7/
Create a java project and add this jar to classpath.
Create a java code
package com.tms.rundown.r.renjin.samples;
/**
*
* @author 157330
*
*/
import java.util.*;
import javax.script.*;
public class TryRenjin {
public void test () throws Exception {
// create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
// create a Renjin engine:
ScriptEngine engine = manager.getEngineByName("Renjin");
// check if engine has loaded correctly:
if (engine == null) {
throw new RuntimeException ("Renjin Script Engine not found on the classpath.");
}
else {
System.out.println ("Renjin Script Engine initialized!");
}
// run R script coded manually
TestLinearRegression (engine);
// run R script from an external .r script file (located in /src/scripts/.)
TestLinearRegressionFromRFile (engine);
}
private void TestLinearRegression (ScriptEngine engine) {
try {
engine.eval ("df <- data.frame(x=1:10, y=(1:10)+rnorm(n=10))");
engine.eval ("print (df)");
// NOTE: The ScriptEngine won’t print everything to standard out like the
// interactive REPL does, so if you want to output something, you’ll need
// to call the R print() command explicitly.
engine.eval ("print(lm(y ~ x, df))");
}
catch (Exception e) {
System.out.println (e);
}
}
private void TestLinearRegressionFromRFile (ScriptEngine engine) {
try {
System.out.println ("here " + (new Date ()));
engine.eval (new java.io.FileReader ("C:\\Rworkspace\\RSamples\\Script.R"));
}
catch (Exception e) {
System.out.println (e);
}
}
public static void main(String[] args) throws Exception {
TryRenjin renjin = new TryRenjin();
renjin.test();
}
}
Script.R
df <- data.frame(x=1:10, y=(1:10)+rnorm(n=10))
print(df)
print(lm(y ~ x, df))
Output: <lm à Linear regression in java with R requires jdk 7 to use renjin : java.util.objects>