Call Java in R Using Package rJava
Posted on Jun 23, 2012 in Computer Science
Things under legendu.net/outdated are outdated technologies that the author does not plan to update any more. Please look for better alternatives.
The package "rJava" offers a convenient way to call Java code from R. The following are some tips for using the "rJava" package.
-
You must first start a Java Virtual Machine using
.jinit
before calling Java code from R. You can specifiy a vector of paths for the function.jinit
. If the Java code relies on some other package or jar files, their path must also be added to the search path of the Java Virtual Machine. Notice the the class paths must be full paths rather than relative paths. If you develop an R package depending onrJava
, you can.jpackage
to initializes a Java Virtual Machine (JVM) in the function.onLoad
. -
After creating an Java object, you can use
$
to invoke its public methods and access its public fields directly instead of using the function.jcall
or.jfield
. This way preserves the flavor of object oriented programming, and is much more convenient. -
You can use boolean values, double values, strings directly when invoking Java methods in R. Because numerical numbers are double numbers be default in R, you should either add suffix "L" to a number or use function
as.integer
to convert it to an integer if you want to pass it as an integer to a Java method. -
You can call a static method of class using the function
.jcall
. Just replace the object argument with the name of the class whose static method you want to call. -
To pass an vector to a Java method, you have to use the function
.jarray
to convert the vector to a Java array. -
The table of JNI:
I
: integerD
: doubleJ
: long F: float V: void Z: boolean C: charB
: byteL<class\>
: java object of the class <class>, e.g.,Ljava/lang/Object
[<type\>
array of objects of type<type\>
, e.g.[D
for an array of doubles