rJava是一个R语言和Java语言的通信接口,通过底层JNI实现调用,允许在R中直接调用Java的对象和方法。
步骤:
1.本地系统:
Win7 64bit 企业版, jdk1.8.0_45,R3.2.2。
2.在R中安装rJava:
下载好R-3.2.2-win.exe,直接打开。输入:
> install.packages("rJava")
#加载rJava
> library(rJava)
> .jinit()
#R调用Java变量测试
> s <- .jnew("java/lang/String", "Hello World!")
> s
[1] "Java-Object{Hello World!}"
3.设置系统环境变量:
R_HOME: C:\Program Files\R\R-3.2.2
RJAVA_HOME:C:\Program Files\R\R-3.2.2\library\rJava
PATH:%R_HOME%\bin;%R_HOME%\bin\x64;%RJAVA_HOME%\jri\x64;
4.测试代码:
import org.rosuda.JRI.Rengine; /**
* Created by shida.min on 2015/10/27.
*/
public class DemoRJava {
static {
System.loadLibrary("jri");
}
public static void main(String[] args) {
DemoRJava demo = new DemoRJava();
demo.callRJava(args);
}
// -Djava.library.path="C:\Program Files\R\R-3.2.2\library\rJava\jri\x64"
public void callRJava(String[] args) {
System.out.println(System.getProperty("java.library.path"));
Rengine re = new Rengine(args, false, null);
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
} //打印变量
String version = re.eval("R.version.string").asString();
System.out.println(version); //循环打印数组
double[] arr = re.eval("rnorm(10)").asDoubleArray();
for (double a : arr) {
System.out.print(a + ",");
}
re.end();
} }
在工程中导入JRI.jar, JRIEngine.jar, REngine.jar三个包。
使用 IntelliJ idea 作为 java IDE, 设置VM options:
-Djava.library.path="C:\Program Files\R\R-3.2.2\library\rJava\jri\x64"
首次运行后报错:
java.lang.UnsatisfiedLinkError: C:\Program Files\R\R-3.2.2\library\rJava\jri\x64\jri.dll: Can't find dependent libraries
Disconnected from the target VM, address: '127.0.0.1:49750', transport: 'socket'
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1937)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1855)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at com.xy.DemoRJava.<clinit>(DemoRJava.java:10)
Exception in thread "main"
试了许多办法,都没用,后来在http://*.com/questions/19100875/java-r-interface-jri-setup 上找到方法。
把R目录下的所有*.dll文件都拷贝到jdk的bin目录下,并在程序中加上
static {
System.loadLibrary("jri");
}
测试通过,mark。