JavaData & JavaGetting Started with R Using Java

Getting Started with R Using Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

R is one of the most commonly used software packages for statistical computing and graphics and Java is the most commonly used programming language. rJava is a JNI (Java Native Interface)-based, R-to-Java interface with which Java objects may be created and Java methods called and Java fields accessed from R. In this tutorial, we shall get started with using the rJava R package to use Java from R. This tutorial has the following sections:

Setting the Environment

R is supported on Unix-like OS, Windows OS, and Mac OS X. Support for Mac OS Class was discontinued with R 1.7.1. We have used R on Windows OS for which you can download the binaries file.

Installing R

Double-click the binaries file to install R on Windows (see Figure 1). After R has been installed, start R to log in to the R Console.

Installing R
Figure 1: Installing R

Output the R version with the following command:

> R.version

The R version 3.3.1 is used in his tutorial.

Hello R

Create a simple R function to test R. The following hello function takes an arg for its name and outputs a hello message.

> hello <- function( name ) {
   +    sprintf( "Hello, %s", name );
+ }

Invoke the R function with a name String.

> hello("John Smith")

A message gets output:

[1] "Hello, John Smith"
>
>

The hello function and its output is shown in R Console (see Figure 2).

The hello function and its output
Figure 2: The hello function and its output

Installing the rJava Package

To install the rJava package, run the following command:

> install.packages('rJava', dependencies=TRUE,
   repos='http://cran.rstudio.com/')

The rJava package gets installed, as shown in Figure 3.

A successful installation
Figure 3: A successful installation

Initializing the JVM

Before you are able to use any rJava functions, we need to initialize the JVM. The usage of .jinit is shown, as follows.

.jinit(classpath = NULL,
   parameters = getOption("java.parameters"), ...,
   silent = FALSE, force.init = FALSE)

The classpath arg prepends additional classes to the CLASSPATH setting. The parameters arg specifies the parameters with which the virtual machine is to be invoked. The “…” indicates other implementation specific to Java initialization parameters.

The “silent” attribute is set to FALSE by default, indicating that no warnings are issued. Setting “force.init” to TRUE would re-initialize the JVM if it is running. The .jinit returns 0 if the JVM got initialized and a -ve integer if it did not. A +ve integer is returned if the JVM got initialized partially. Before initializing the JVM, the rJava library must be loaded.

> library(rJava)
> .jinit()
>

The preceding function calls are shown in R Console (see Figure 4).

Result of the preceding function calls
Figure 4: Result of the preceding function calls

Before importing any Java packages, the JVM must be initialized or an error gets generated.

> library(rJava)
> javaImport(packages = "java.util")
Error in .jcheck(silent = TRUE) :
   No running JVM detected. Maybe .jinit() would help.
>

The following is an example of providing parameters to set the maximum Java heap size with - Xmx.

>  .jinit(parameters="-Xmx512m")
[1] 0
>

Setting the Classpath

In this section, we discuss how a classpath may be found or set. To list the entries in classpath, use the .jclassPath() function.

> print(.jclassPath())

An output such as the following lists the directories and jars in the classpath.

[1] "C:UsersDeepak VohraDocumentsR
    win-library3.3rJavajava"
[2] "C:apache_sparkrunrecommender
    scala-library-2.10.4.jar"
[3] "C:apache_sparkrunrecommender
    spark-core_2-1.10-1.2.0.jar"

To add directories and jars to the classpath, use the .jaddClassPath(path) function. For example, add the C:ojdbc6.jar jar to the classpath.

>  .jaddClassPath("C:ojdbc6.jar")

Subsequently, if the classpath entries are output, the C:ojdbc6.jar also should get listed.

> print(.jclassPath())
[1] "C:UsersDeepak VohraDocumentsR
    win-library3.3rJavajava"
[2] "C:apache_sparkrunrecommender
    scala-library-2.10.4.jar"
[3] "C:apache_sparkrunrecommender
    spark-core_2-1.10-1.2.0.jar"
[4] "C:ojdbc6.jar"
>

Creating a Java Object

The .jnew function creates a new Java object. It has the following usage:

.jnew(class, ..., check=TRUE, silent=!check)

The class arg specifies the class name for which a new object is to be created, and the subsequent “…” indicates the args to be passed to the class constructor. The check=TRUE arg invokes the .jcheck function before and after invoking the class constructor to clear any Java exceptions. The silent arg indicates if errors if any are to be output and, if set to FALSE, if creating an object generates an error the error is output and the object creation fails. Otherwise, a null reference is returned if creating an object fails due to an error. It is meaningful to set only silent=!check because, if exceptions are not being checked with a check=FALSE setting, they cannot be output, even with a silent=FALSE setting.

As an example, create a new String object initialized with a “Hello World!” String. Subsequently, output the String object.

> s <- .jnew("java/lang/String",
   "Hello World!")
> print(s)

The Java object created is output.

[1] "Java-Object{Hello World!}

A sequence of commands loading the rJava library, initializing the JVM, creating a String object, and outputting the String object and the output is shown in the R Console (see Figure 5).

Creating and outputting a String object
Figure 5: Creating and outputting a String object

Calling a Java Method

The .jcall function is used to call a Java method. With only the required function parameters, the usage is as follows.

.jcall(obj, returnSig = "V", method, ...)
Parameter Description
obj The object reference as returned from .jnew or .jcall, or fully qualified class name such as java/lang.String.
returnSig = “V” Return signature in JNI notation. For example, to return void set to “V” or to return an int[] set as “I”, or to return a java/lang/String, set as “S”.
method The method to be called.
Optionally, provide any args with which the method is to be invoked.

As an example, using the object reference “s” returned in the previous section, invoke the .jcall method to call the “length” method of the String object and return an int.

> .jcall(s,"I","length")

A value of 12 is returned, which is the length of the “Hello World!” String.

[1] 12

An alternative short form to invoke the length method using the object reference “s” is with objectRef$method() notation. For example, the preceding method call also could be made as follows, outputting 12.

> s$length()
[1] 12
>

The .jstrVal function could be used to call the toString() method of a String object to output the String value. For example, to output the String value of the same String object “s”, invoke the .jstrVal method as follows:

> .jstrVal(s)

The String reference value should get output.

[1] "Hello World!"

The output from preceding function calls is shown in R Console, as shown in Figure 6.

Output from the "Hello World!" function call
Figure 6: Output from the “Hello World!” function call

A Java method also may be called using J, which is a high-level API for accessing Java. J creates a Java class reference or calls a Java method and has the following usage:

J(class, method, ...)

Only the “class” arg is required and is the Java object reference or the fully qualified class name specified in JNI notation, such as java/lang/String or Java notation, such as java.lang.String. As an example, call the parseDouble method in Java class java.lang.Double with method arg “10.2”.

> J("java.lang.Double", "parseDouble", "10.2")

The method call should return the double value.

[1] 10.2

To invoke a static method, also called a class method, the $ operator could be used on the Java class reference. As an example, call the static method parseDouble(String s) in the java.lang.Double class as follows, with the arg supplied to the parseDouble method as “10.2”.

>
J("java.lang.Double")$parseDouble("10.2")

An output of double value 10.2 is returned.

[1] 10.2

The output from the preceding method calls in R Console is as follows (see Figure 7).

Returning "10.2"
Figure 7: Returning “10.2”

In the next article,”Using Java Strings and the Swing API in R,” we shall explore using Strings further. We also shall discuss creating a Java Swing application in R. Another feature discussed in the next article is finding whether an object is an instance of a class.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories