Setup rJava on Mac and start using openNLP

rJava installation on Mac

rJava library is important for RStudio and if you are working with java based packages such as openNLP

By Fahad Usman

Are you getting this error when installing rJava?

> library(rJava)
Error: package or namespace load failed for ‘rJava’:
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(file, DLLpath = DLLpath, ...)
  error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib/server/libjvm.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so
  Reason: image not found

Then read on and see how you could fix it!

The first thing you need to do is to check if you have java installed, open up the terminal and type:

java -version

if you get a message like:

No Java runtime present, requesting install.

This means no java is installed on your Mac. Another pop-up message window will appear asking you to click on "More Info" button.

This will open up your default browser and take you to java download page.

Click the link Java Platform (JDK) and it will take you to another page. Just accept the licence terms and download the .dmg file and install it as normal.

Once installed, confirm again in the terminal by typing:

java -version

This should spit out something like this:

java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)

Also confirm if javac is being installed as well by typing in the terminal:

javac -version

and it should output something like:

javac 11.0.1

Setting up JAVA_HOME

The next step is to setup JAVA_HOME environment variable. In the terminal type:

echo $JAVA_HOME

It should show nothing. This means that $JAVA_HOME is not being setup.

goto your Home directory by cd ~/ and then type ls -la and confirm if the file .bash_profile exists.

if the file is not present then just create it by touch .bash_profile.

edit the file using vim .bash_profile and press enter

Now add the following line and save and close the file:

export JAVA_HOME=$(/usr/libexec/java_home)

Now close the terminal and open a new terminal and type:

echo $JAVA_HOME

you should see something like:

/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home

Now Tell R to use our Java 11 as it’s JAVA_HOME

Go back to the terminal and type:

sudo R CMD javareconf

You should see something like this:

And That’s it! Go back to RStudio and restart it. Now run the final two commands:
install.packages("rJava")
library(rJava)
You shouldn't see any error now 🙂

Leave a Reply

Close Menu