我正在使用 maven,所以我有以下内容(从一个简单的 maven 项目生成)
mvn archetype:generate -DgroupId=com.test.rserve -DartifactId=com.test.rserve
选择默认选项。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.rserve</groupId>
<artifactId>com.test.rserve</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>com.test.rserve</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.rosuda.REngine</groupId>
<artifactId>Rserve</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
</project>
应用程序.java
package com.test.rserve;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class App {
public static void main(String[] args) throws RserveException,
REXPMismatchException {
RConnection c = new RConnection();
REXP x = c.eval("R.version.string");
System.out.println(x.asString());
c.eval("library(GWmodel)");
c.eval("data(LondonHP)");
c.eval("DM <- gw.dist(dp.locat=coordinates(londonhp))");
REXP y = c.eval("dim(DM)[1]");
System.out.println(y.asString());
c.close();
}
}
确保软件包 Rserve 已安装在您的 R 环境中。
来自 R
library(Rserve)
Rserve()
使用 maven(命令行,另一个 shell)
mvn exec:java -Dexec.mainClass="com.test.rserve.App"
我们得到我的设置:
R version 3.2.4 (2016-03-16)
316
之后不要忘记关闭 Rserve 服务器/进程...