Installing rJava

Installing the {rJava} package on Ubuntu is not quite as simple as most other R packages. Some quick notes on how to do it.

Ubuntu

  1. Update the repository listings.
sudo apt update -y
  1. Install the Java Runtime Environment (JRE) and Java Development Kit (JDK).
sudo apt install -y openjdk-8-jdk openjdk-8-jre
  1. Update where R expects to find various Java files.
sudo R CMD javareconf

If you get an error about jni.h not being found, then try this:

sudo R CMD javareconf JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
  1. Install the package.
install.packages("rJava")
  1. If you have a RStudio session open, then exit and restart it. This is important (a running RStudio session will not pick up these changes!).

Sorted!

🚨 The recipe above is based on older versions of JRE and JDK. With more recent versions you can install the packages like this:

sudo apt install -y default-jdk

Then look under /usr/lib/jvm/ to find the appropriate directory to use for JAVA_HOME.

Jupyter Docker

A different approach if you are installing into a Docker image.

FROM jupyter/r-notebook:r-4.3.1

USER root

RUN apt update -y

RUN apt install -y default-jdk

ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
ENV LD_LIBRARY_PATH=${JAVA_HOME}/lib/server:${LD_LIBRARY_PATH}

RUN R CMD javareconf

RUN R -e 'install.packages("rJava", repos="https://cran.r-project.org")'