Installing rJava for R on the Mac

Introduction

There are several R packages that link to or use Java, and so there exists a link between R and Java throught the rJava package. The rJava package is notoriously finicky to install in R, given the quirks of the Mac OS X system, Java, and R. In fact general advice is that, if you can avoid using rJava, do. It is a conundrum that even the most experienced R hands would like to avoid.

I recently went through the process of installing rJava on a new MacBook Pro, using advice from the web. I’ll document the process I followed, with the following software:

  • Mac OS X Sierra (version 10.12.6)
  • Java JDK version 9.0.1
  • R version 3.4.2 (Short Summer) 64-bit
  • rJava version 0.9-9, installed from source

Setting the groundwork

First, we need to install the Xcode command line tools using the code

xcode-select --install

Next we install both Java 6 and the current Java version. Java 6 is apparently needed for some scaffolding and functions not present in the current version. All commands below need to be run in a Terminal.

Java 6

curl -#ROL https://support.apple.com/downloads/DL1572/en_US/javaforosx.dmg
open javaforosx.dmg

and walk through the installation.

Java 9

Install the JDK package from this link

To ensure that Java is installed, run the following functions in the Terminal

/usr/libexec/java_home -V
java -version

I get these results:

[~] /usr/libexec/java_home -V                                                  

Matching Java Virtual Machines (3):
    9.0.1, x86_64:  "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    1.6.0_65-b14-468, x86_64:   "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
    1.6.0_65-b14-468, i386: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
[~] java --version                                                             
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

Setting up clang and other required software

I installed r-macos-clang using the installer available here. This took care of installing the version of the clang compiler compatible with the current R version.

This still had some problems in terms of finding some files. I then ran the following lines in the Terminal:

sudo ln -f -s $(/usr/libexec/java_home)/jre/lib/server/libjvm.dylib /usr/local/lib
sudo ln -s /usr/local/clang4/lib/libomp.dylib /usr/local/lib/libomp.dylib

Setting up Java for R

Run the following two commands in the Terminal:

unset JAVA_HOME
R CMD javareconf

Installing rJava

From the Terminal, I ran the following command:

R --quiet -e 'install.packages("rJava", type="source", repos="http://cran.us.r-project.org")'

This compiles rJava from source, and for me this worked.