How to do it...

To use Java objects in R, follow these steps:

  1. From within R, start the JVM, check the Java version, and set classpath:
> .jinit() 
 
> .jcall("java/lang/System", "S", "getProperty", "java.runtime.version") 
[1] "1.8.0_25-b17" 
 
> .jaddClassPath(getwd()) 
 
> .jclassPath() 
[1] "/Library/Frameworks/R.framework/Versions/3.1/Resources/library/rJava/java" 
[2] "/Users/sv/book/Chapter11"  => my working directory 
  1. Perform these Java string operations in R:
> s <- .jnew("java/lang/String", "Hello World!") 
> print(s) 
 [1] "Java-Object{Hello World!}" 
 
> .jstrVal(s) 
[1] "Hello World!" 
 
> .jcall(s,"S","toLowerCase") 
[1] "hello world!" 
 
> .jcall(s,"S","replaceAll","World","SV") 
[1] "Hello SV!"
  1. Perform these Java vector operations:
> javaVector ...

Get R Data Analysis Cookbook - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.