【发布时间】:2017-03-09 20:46:21
【问题描述】:
我用 Java (eclipse) 编写了一个小程序来使用 JRI (rjava) 运行 R。所有路径都设置好了。问题是虽然我可以运行数字函数(如add),但我不能运行像cat 这样的字符串函数。 (请原谅任何错误;我昨天第一次进行 Java 编码)。
package com.trial.ss;
import org.rosuda.JRI.Rengine;
public class RScriptConnection {
public Rengine getRScriptEngine() throws Exception {
Rengine engine = null;
try {
engine = Rengine.getMainEngine();
if (engine == null) engine = new Rengine(new String[] {
"--vanilla"
},
false, null);
/* if (!engine.waitForR()) {
System.out.println("Unable to load R");
return null;
} else*/
System.out.println("Connected to R");
String rScriptSourceFile = "source('" + RScriptConstant.RS_FILE_LOCATION + "',verbose=TRUE)";
engine.eval(rScriptSourceFile);
System.out.println("loading RScript file || completed");
//return engine;
} catch(Exception ex) {
System.out.println("Exeption while connecting to REngine " + ex.getMessage());
//throw new Exception("Error while creating REngine in RScriptConnection:getRScriptEngine()");
}
return engine;
}
public static void main(String[] args) {
String libpath = System.getProperty("java.library.path");
System.out.println("##############libpath=" + libpath);
// System.out.println("Method to be called in RScript=" + "Add(x1 = " + 10 + ", x2 = " + 20 + ", x3 = " + 30 + ", x4 = " + 50 + ")");
RScriptConnection rScriptConnection = new RScriptConnection();
try {
Rengine rEngine = rScriptConnection.getRScriptEngine();
String Value1 = "\"Advisory\"";
String Value2 = "\"Assurance\"";
double svalue = rEngine.eval("(1+2)").asDouble();
System.out.println("mvalue=" + svalue);
System.out.println("method to be called in RScript is " + "cat(" + Value1 + "," + Value2 + ")");
String value = rEngine.eval("cat(" + Value1 + "," + Value2 + ")").asString();
System.out.println(value);
rEngine.end();
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
请帮助我理解为什么像cat 这样的字符串函数不起作用。
这是我目前得到的输出:
##############libpath=C:\Users\myname\Documents\R\win-library\3.3\rJava\jri\x64
Connected to R
loading RScript file || completed
mvalue=3.0
method to be called in RScript is cat("Advisory","Assurance")
null
为什么我最后会得到null?我应该得到Advisory Assurance
【问题讨论】:
-
它不会自动为您将 R 控制台“stdout”连接到 Java“stdout”。您可以通过 rforge.net/org/docs/org/rosuda/JRI/…, boolean, org.rosuda.JRI.RMainLoopCallbacks)> 获得控制台输出的自动回调,但这意味着有一个主循环。使用
capture.output()包装cat调用将使您能够以字符串形式获取结果(在示例代码中分配给value)。您可以将, file='/some/dir/and/file.txt'添加到您的cat调用中,然后读取该文件的输出。