我正在尝试使用Java和R(JRI和Rengine)绘制一些图形。当我在代码中编写如下代码时,效果很好:
re.eval("plot(c(1,5,3,8,5), type='l', col=2)");
但是如果我这样写:
re.eval("source(\"C:\\Documents and Settings\\abc\\My Documents\\Test Data\\BoxPlot.r\");");
输出窗口闪烁片刻并消失。此指定文件仅包含一个命令,第一个命令即
re.eval("plot(c(1,5,3,8,5), type='l', col=2)");
我对R非常陌生,所以这可能是一个非常基本的问题。但是我找不到它。谁能帮我吗?
谢谢。
编辑1
我正在使用Windows XP。
这是完整的代码:
import org.rosuda.JRI.Rengine;
public class JavaGDExample1 {
public static void main(String[] args) {
Rengine re;
String[] dummyArgs = new String[1];
dummyArgs[0] = "--vanilla";
re = new Rengine(dummyArgs, false, null);
re.eval("library(JavaGD)");
// This is the critical line: Here, we tell R that the JavaGD() device that
// it is supposed to draw to is implemented in the class MyJavaGD. If it were
// in a package (say, my.package), this should be set to
// my/package/MyJavaGD1.
re.eval("Sys.putenv('JAVAGD_CLASS_NAME'='MyJavaGD1')");
re.eval("JavaGD()");
// re.eval("plot(c(1,5,3,8,5), type='l', col=2)");
re.eval("source(\"C:\\Documents and Settings\\abc\\My Documents\\Test Data\\BoxPlot.r\");");
// re.eval("source(\"C:\\Documents and Settings\\abc\\My Documents\\Test Data\\testPlot.r\")");
re.end();
}
}
import javax.swing.JFrame;
import org.rosuda.javaGD.GDCanvas;
import org.rosuda.javaGD.GDInterface;
/**
* This is a minimal reimplementation of the GDInterface. When the device is opened,
* it just creates a new JFrame, adds a new GDCanvas to it (R will plot to this GDCanvas)
* and tells the program to exit when it is closed.
*/
public class MyJavaGD1 extends GDInterface {
public JFrame f;
public void gdOpen(double w, double h) {
f = new JFrame("JavaGD");
c = new GDCanvas(w, h);
f.add((GDCanvas) c);
f.pack();
f.setVisible(true);
f.setTitle("Naked R plot");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
最佳答案
您的路径错误-您正在输入引号 hell ,您发送给R的是
source("C:\Documents and Settings\abc\My Documents\Test Data\BoxPlot.r");
这是无效的:
> source("C:\Documents and Settings\abc\My Documents\Test Data\BoxPlot.r");
Error: '\D' is an unrecognized escape in character string starting "C:\D"
为避免引号,指定文件名更安全:
re.assign("fn", "c:\\foo\\bar");
re.eval("source(fn)");
或使用
/
代替\\
PS:使用stats-rosuda-devel解决rJava / JRI问题