官方文档:https://www.rforge.net/rJava/

一、介绍

rjava是一个简单的R-to-Java的接口。rjava通过JNIRjava之间建立了桥梁。从而可以在R中创建java对象,调用java方法。目前,rJava用作JGRiPlotsJavaGD软件/软件包的一部分。

二、安装Rjava

install.packages('rJava')

三、Rjava的简单使用

调用java计算字符串长度

library(rJava)
.jinit() # this starts the JVM
s <- .jnew("java/lang/String", "Hello World!")
.jcall(s,"I","length")
# [1] 12

创建Jframe窗口

library(rJava)
.jinit() # this starts the JVM
f <- .jnew("java/awt/Frame", "Hello")
b <- .jnew("java/awt/Button", "OK")
.jcall(f, "Ljava/awt/Component;", "add", .jcast(b, "java/awt/Component"))
.jcall(f,, "pack")
.jcall(f,, "setVisible", TRUE)

四、安装可能存在的问题

问题

*** Cannot find any Java interpreter
*** Please make sure 'java' is on your PATH or set JAVA_HOME correspondingly

原因:在ubuntu root用户没有JAVA_HOME, 创建脚本, 使用root用户运行

#!/bin/bash
export JAVA_HOME="<path to jdk>"
R CMD javareconf

运行结果

Java interpreter : /home/wy/softwere/jdk1.8.0_231//jre/bin/java
Java version     : 1.8.0_231
Java home path   : /home/wy/softwere/jdk1.8.0_231/
Java compiler    : /home/wy/softwere/jdk1.8.0_231//bin/javac
Java headers gen.: /home/wy/softwere/jdk1.8.0_231//bin/javah
Java archive tool: /home/wy/softwere/jdk1.8.0_231//bin/jar

trying to compile and link a JNI program 
detected JNI cpp flags    : -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
detected JNI linker flags : -L$(JAVA_HOME)/jre/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG -I/home/wy/softwere/jdk1.8.0_231//include -I/home/wy/softwere/jdk1.8.0_231//include/linux     -fpic  -g -O2 -fdebug-prefix-map=/build/r-base-AitvI6/r-base-3.4.4=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
g++ -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o conftest.so conftest.o -L/home/wy/softwere/jdk1.8.0_231//jre/lib/amd64/server -ljvm -L/usr/lib/R/lib -lR


JAVA_HOME        : /home/wy/softwere/jdk1.8.0_231/
Java library path: $(JAVA_HOME)/jre/lib/amd64/server
JNI cpp flags    : -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
JNI linker flags : -L$(JAVA_HOME)/jre/lib/amd64/server -ljvm
Updating Java configuration in /usr/lib/R
Done.