我正在使用Java进行基于rserve调用R的项目。当我在Java中执行R代码时,我会遇到错误。
这是我的Java代码:
xp=c.eval("eperson(economic)");
System.out.println("----eperson(economic).asList()-----");
//System.out.println(xp.length());
for(int i=0;i<xp.asInteger();i++){
System.out.println(xp.asStrings()[i]);
}
我所拥有的是:
org.rosuda.REngine.REXPMismatchException: attempt to access org.rosuda.REngine.REXPGenericVector as int
我在rstudio中运行了代码,结果如下:
> eperson(economic)
[[1]]
[1] "主成份分析结果为"
[[2]]
Importance of components:
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7
Standard deviation 2.1124391 1.1491308 0.9331551 0.50448791 0.2699638 0.137595030 0
Proportion of Variance 0.6374856 0.1886431 0.1243969 0.03635829 0.0104115 0.002704627 0
Cumulative Proportion 0.6374856 0.8261287 0.9505256 0.98688388 0.9972954 1.000000000 1
Loadings:
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 Comp.6 Comp.7
x1 -0.446 0.127 0.138 0.431 0.599 0.241 -0.404
x2 -0.467 0.268 0.837
x3 -0.445 0.146 -0.243 -0.671 0.451 -0.260
x4 -0.377 -0.377 0.168 -0.763 0.236 0.223
x5 -0.257 -0.297 -0.819 0.162 -0.382
x6 -0.418 0.280 0.337 -0.137 -0.196 -0.730 -0.208
x7 0.808 -0.319 -0.375 0.265 0.150
[[3]]
[1] "综合得分和经济人口承载力为"
[[4]]
年份 指数 承载人口
1 2006 2.2589596 178.29831
2 2007 1.9662692 155.19644
3 2008 1.6925468 133.59169
4 2009 0.2778931 21.93393
5 2010 0.8682956 68.53405
6 2011 1.8017713 142.21272
7 2012 2.9307567 231.32285
我如何在我的Java代码中显示与Rstudio中相同的结果?
如果您只是有兴趣打印结果,将结果存储在r中,然后通过Java捕获该变量的输出作为字符串:
c.eval("mod <- eperson(economic)");
String ret = c.eval("paste(capture.output(mod),collapse='\n')").asString();
System.out.print(ret);