Search code examples
javarrserve

attempt to access org.rosuda.REngine.REXPGenericVector as int


I'm doing a project using Java to call R based on Rserve.When I execute R code in Java,I get an error.

This is my java code:

    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]);
 }

What I have got is:

org.rosuda.REngine.REXPMismatchException: attempt to access org.rosuda.REngine.REXPGenericVector as int

I ran the code in the RStudio, and the results were as follows:

> 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

How can I show the same result in my java code as it is in RStudio ?


Solution

  • If you're just interested in printing the results, store the results as a variable in R, and then capture the output of that variable as a String through java:

    c.eval("mod <- eperson(economic)");
    String ret = c.eval("paste(capture.output(mod),collapse='\\n')").asString();
    System.out.print(ret);