1

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)

Community
  • 1
  • 1

2 Answers2

0

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());
LoveTW
  • 3,746
  • 12
  • 42
  • 52
0

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.

alf
  • 8,377
  • 24
  • 45
  • Thanks for the input but I already tried that ' System.out.println( x.asDouble()); System.out.println( x.asDoubleArray());' gives me '0.0' and 'null' – user1032624 Nov 06 '11 at 19:21
  • I've got no `"source(\"/..../TS.R\")"`—hence cannot check your code. Could you give a http://sscce.org/ please? – alf Nov 06 '11 at 19:33
  • `x.asDouble())` would not work, since x is not a scalar. See the update. – alf Nov 06 '11 at 19:40
  • I need to think over it again, sscce is not so easy because of dependencies. I have a feeling that my R data type could be the problem. – user1032624 Nov 06 '11 at 19:45
  • Check the update first; it well may be you have no problem yet :) – alf Nov 06 '11 at 19:48
  • Figured it out :D. Running the R code using `"source(...)"` was the problem it returns `"[VECTOR ([REAL* (3.050462038715372)], [BOOLi* ])]"` instead of `"[REAL* (3.050462038715372)]"`. A separate call to get the results (using your answer) solved the problem. Thanks for the help!!! – user1032624 Nov 06 '11 at 20:18