我正在尝试从我的Java代码中执行一个R脚本。这是我的java代码
package pkg;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class Temp {
public static void main(String a[]) {
RConnection connection = null;
try {
/* Create a connection to Rserve instance running on default port
* 6311
*/
connection = new RConnection();
connection.eval("source('D:\\\\r script\\\\TestRserve.R')");
connection.eval("Rserve()");
int num1=10;
int num2=20;
int sum=connection.eval("myAdd("+num1+","+num2+")").asInteger();
System.out.println("The sum is=" + sum);
} catch (RserveException e) {
e.printStackTrace();
} catch (REXPMismatchException e) {
e.printStackTrace();
}
}
}R如下所示
library(Rserve)
Rserve()
x= matrix(c(1,2,3,4,5,6))
plot.ts(x)我使用了教程和AFAIK中的示例代码,TestRserve没有在Java文件中执行。我还尝试了下面这样的方法来执行TestRserve.R
REXP x;
System.out.println("Reading script...");
File file = new File("D:\\r script\\TestRserve.R");
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
System.out.println(line);
x = c.eval(line); // evaluates line in R
System.out.println(x); // prints result
}
}下面是堆栈跟踪
线程"main“中的异常:无法连接:连接被拒绝:连接在org.rosuda.REngine.Rserve.RConnection.(RConnection.java:88) at org.rosuda.REngine.Rserve.RConnection.(RConnection.java:60) at org.rosuda.REngine.Rserve.RConnection.(RConnection.java:44) at functionTest.HelloWorldApp.main(HelloWorldApp.java:17)
发布于 2016-08-17 20:43:56
从您的代码中可以看出对Rserve的一堆误解。
首先,Rserve是一个服务器,Rserve文件提供客户端实现来与Rserve交互,就像npm上有npm客户机一样。
因此,要通过Rserve调用R脚本,需要启动Rserve服务器并等待接收呼叫。这可以通过以下方法从R中实现:
library(Rserve)
Rserve()或者,:直接从linux调用R CMD Rserve --vanilla,或者使用JavaRuntime API直接调用它来访问运行时:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");虽然这也适用于linux。
然后,您应该执行Java客户端代码,通过Rserve连接到Rserve服务器和eval()所有R命令。
https://stackoverflow.com/questions/38970392
复制相似问题