Talking R through Java
To talk to R through Java you have to specify three more environmental variables. First of all you need to publish you R installation path, my R is found in
If you didn’t or the path is wrong you’ll fall into trouble:
$CLASSPATH needs to get an update. Precisely you have to add the archives
REngine.jar . In my case all of them can be found in
/usr/lib/R/site-library/rJava/jri/ , so the
$CLASSPATH should be set like that:
$CLASSPATH isn’t defined correctly you won’t be able to compile your Java code.
Last but not least you have to add the native JRI-library to your
$LD_LIBRARY_PATH , by default this lib is located in the same directory like the jar’s:
$LD_LIBRARY_PATH isn’t proper you’ll experience errors like this:
To not always do the same you might write these export stuff to your
Of course in Eclipse you’ll also have to define these three things.
Where are the jar’s located? Add them to your libraries in Project > Properties > Java Build Path > Libraries.
Instead of the
$LD_LIBRARY_PATH you can set the
java.library.path in Run > Run Configurations > Arguments. Add
-Djava.library.path=.:/usr/lib/R/site-library/rJava/jri/ to the VM arguments (modify the path to match your criteria).
R_HOME can be published in Run > Run Configurations > Environment. Create a new variable with the name
R_HOME and the value
/usr/lib64/R (or an equivalent path).
That’s it, see the section above to identify what went wrong if something fails.
Two of these three parts are also straight forward in Netbeans.
First publish the location of the jar’s. Right-click on your project and choose Properties > Libraries. In the Compile-tab click Add JAR/Folder and search for the jar files.
Next task is to adjust the library-path. Right-click on your project and choose Properties > Run. Add
-Djava.library.path=.:/usr/lib/R/site-library/rJava/jri/ to the VM Options (modify the path to match your criteria).
The third step is a little tricky. As far as I know there is no way to change the environment from within Netbeans, so you can’t create the variable
R_HOME after Netbeans is started. In my opinion you have two options:
- Export the variable before starting Netbeans:
you might want to write a wrapper script that does this step for you, or include the export in any of the resource files that are called before Netbeans starts (e.g. your
- Change the environment from within your project. At stackoverflow you can find a workaround, but I think this is a very lousy solution..
If you defined your environment properly, you should be able to utilize the REngine. I have a small script for you to test whether all things are fine:
You should be able to compile and run it, afterwards you’ll see a random number from an uniform distribution. Congratulations, well done :-P