-->

Call R from Java using JRI, how to cast return val

2019-07-26 09:00发布

问题:

I'm executing some R commands from Java using JRI.I want to use the results from R in my Java for further calculations but I have no idea how cast the returned object.

call code in Java:

REXP x;
System.out.println(x = rengine.eval("source(\"/..../TS.R\")"));
System.out.println( x.asVector().elementAt(0));

last line from R code:

eq_all[length(eq_all)-1]

--

output in Java console:

[VECTOR ([REAL* (3.050462038715372)], [BOOLi* ])]
[REAL* (3.050462038715372)]

"3.050462038715372" is the right value but how can I access it in Java?

best regards, Immanuel

PS. related question without answer: Converting REXP object to a double array (Java/R)

回答1:

I believe asDouble() and asDoubleArray() are what you need.

Update: So on your code example, it should be:

REXP x;
System.out.println(x = rengine.eval("source(\"/..../TS.R\")"));
System.out.println(x.asVector().elementAt(0).asDouble());

PS. The referred question actually had the answer you needed—the problem there is with implementation of toString() in Java arrays.



回答2:

elementAt() is not working, your could use at().

REXP x;
System.out.println(x = rengine.eval("source(\"/..../TS.R\")"));
System.out.println(x.asVector().at(0).asDouble());


标签: java r jri rjava