我想将一个R脚本运行到eclipse中。
Jars:
环境(运行 - >运行配置 - >环境)
代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.rosuda.JRI.Rengine;
public class HelloWorldApp {
public static void main(String[] args) throws RserveException, REXPMismatchException, FileNotFoundException, IOException {
RConnection c = new RConnection("localhost",6311);
if(c.isConnected()) {
System.out.println("Connected to RServe.");
if(c.needLogin()) {
System.out.println("Providing Login");
c.login("username", "password");
}
REXP x = c.eval("1:10");
for(int i=0;i < x.length();i++)
{
System.out.println(x.asIntegers()[i]);
}
System.out.println("Reading script...");
Rengine r = new Rengine(args, true, null);
r.eval(" plot (x");
} else {
System.out.println("Rserve could not connect");
}
c.close();
System.out.println("Session Closed");
}
}
输出:
Connected to RServe.
1
2
3
4
5
6
7
8
9
10
Reading script...
Fatal error: you must specify '--save', '--no-save' or '--vanilla'
Rstudio中发生了同样的错误:
library("Rserve")
Rserve()
输出:
Starting Rserve:
/usr/local/lib/R/bin/R CMD /home/mansi/R/x86_64-unknown-linux-gnu-library/3.1/Rserve/libs//Rserve
Fatal error: you must specify '--save', '--no-save' or '--vanilla'
所以请帮我解决这个致命的错误。
答案 0 :(得分:9)
Try: Rserve(args='--vanilla')
我遇到了同样的问题,这对我有用。
答案 1 :(得分:2)
您可以使用rJava包附带的JRI而不是RServe。
在我看来,JRI比RServe更好,因为它不是创建一个单独的进程,而是使用本机调用来集成Java和R.
使用JRI,您不必担心端口,连接,监视器等...对R的调用是使用操作系统库(libjri)完成的。
这些方法与RServe非常相似,您仍然可以使用REXP对象。
有一个例子:
public void testMeanFunction() {
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch - Java files don't match library version.");
fail(String.format("Invalid versions. Rengine must have the same version of native library. Rengine version: %d. RNI library version: %d", Rengine.getVersion(), Rengine.rniGetVersion()));
}
// Enables debug traces
Rengine.DEBUG = 1;
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) no callback class will be used
engine = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine", new String[] { "--no-save" }, null, false);
System.out.println("Rengine created...");
engine.parseAndEval("rVector=c(1,2,3,4,5)");
REXP result = engine.parseAndEval("meanVal=mean(rVector)");
// generic vectors are RVector to accomodate names
assertThat(result.asDouble()).isEqualTo(3.0);
}
我有一个演示项目,它公开了一个REST API并使用这个包来调用R函数。