Developer

phoen1x

A clever man solves a problem, a wise man avoids it.
— Albert Einstein

Combine Java and R with rJava

R is a programming language for statistical computing and well known for its capability to plot data. With this minimalistic tutorial you can run R calculations from your Java source code. See this Youtube video for details.

Contents

Install rJava

# make shure R is installed
R --version

# install R package - https://github.com/s-u/rJava
Rscript -e 'install.packages("rJava",,"http://rforge.net")'

# make sure rJava can find the Java runtime
# ls -la /usr/lib/jvm/default-java/jre/bin/java
# symlink the Java runtime if this path does not exist
# sudo  ln -s /usr/lib/jvm/java-8-oracle /usr/lib/jvm/default-java

Run rJava demo

# get rJava project
git clone https://github.com/s-u/rJava.git

# create project folder
mkdir -p rJava/jri/examples/spring
cd $_

# download demo project --> curl https://start.spring.io
curl    -o starter.zip \
        -d groupId="org.rosuda.spring" \
        -d artifactId="demo" \
        -d version="0.0.1" \
        -d bootVersion="1.5.7.RELEASE" \
    https://start.spring.io/starter.zip

# unpack and cleanup
unzip starter.zip && rm starter.zip

# create Demo Programm
echo 'package org.rosuda.spring.demo;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class DemoRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        Rengine.versionCheck();
        Rengine rengine = new Rengine(new String[] { "--no-save" }, false, null);
        REXP rValue = rengine.eval("capture.output(summary(rnorm(500)))");
        System.out.println(
                String.format(
                        "\\n\\n\\nStatistics of 500 random numbers:\\n\\n%s\\n%s\\n\\n\\n",
                            rValue.asStringArray()[0],
                            rValue.asStringArray()[1]));
        rengine.end();
    }
}' > src/main/java/org/rosuda/spring/demo/DemoRunner.java

# copy JRI
mkdir -p src/main/java/org/rosuda/JRI
cp ../../*.java $_

# setup shell variables -> script setupShell.sh (see below)
export LOCAL_RJAVA_PATH=$(Rscript -e 'cat(installed.packages()[Package="rJava","LibPath"])')
export LOCAL_JRI_PATH="$LOCAL_RJAVA_PATH/rJava/jri/"
source $LOCAL_JRI_PATH/run &> /dev/null

# run demo
MAVEN_OPTS="-Djava.library.path=$LOCAL_JRI_PATH" ./mvnw spring-boot:run

# run jar with setupShell.sh (see below)
source setupShell.sh
./mvnw -DskipTests=true clean package
java -Djava.library.path=$LOCAL_JRI_PATH -jar target/demo-0.0.1.jar

Expected Demo output

      ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
     |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
:: Spring Boot ::        (v1.5.7.RELEASE)

Statistics of 500 random numbers:

    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
-3.09235 -0.61386 -0.02619 -0.02362  0.64639  2.31572

setupShell.sh

#!/bin/bash

# make shure R is installed
Rscript --version &> /dev/null
if [[ $? -ne 0 ]]; then
    echo -e "\e[31myou need to install R\e[39m"
    exit 1
fi

# set the path where you installed JRI
# Rscript -e 'installed.packages()[Package="rJava","LibPath"]'
export LOCAL_RJAVA_PATH=$(Rscript -e 'cat(installed.packages()[Package="rJava","LibPath"])')
if [[ $? -ne 0 ]]; then
    echo -e "
    \e[31mrJava path not found\e[39m

    # install R package - https://github.com/s-u/rJava
    \e[32mRscript -e 'install.packages(\"rJava\",,\"http://rforge.net\")'\e[39m

    # make sure rJava can find the Java runtime
    # ls -la /usr/lib/jvm/default-java/jre/bin/java
    # symlink the Java runtime if this path does not exist
    # sudo  ln -s /usr/lib/jvm/java-8-oracle /usr/lib/jvm/default-java
"
    exit 1
fi

export LOCAL_JRI_PATH="$LOCAL_RJAVA_PATH/rJava/jri/"
echo -e "\nLOCAL_RJAVA_PATH:  \e[33m$LOCAL_RJAVA_PATH\e[39m"
echo -e "LOCAL_JRI_PATH:  \e[33m$LOCAL_JRI_PATH\e[39m"

# QUICK AND DIRTY setup rJava shell variables with the run script
source $LOCAL_JRI_PATH/run &> /dev/null
echo -e "R_HOME:  \e[33m$R_HOME\e[39m\n"

Back ...