Converting REXP object to a double array (Java/R)

回眸只為那壹抹淺笑 提交于 2019-12-23 14:38:51

问题


I want R to produce, for example, normal data and then use this data in Java. I know there is a function to convert an REXP object to an array but it doesn't seem to work. Here is what I have:

REXP x;
x = re.eval("rnorm(100,50,10)");
double[] test = x.asDoubleArray();
System.out.println(x);
System.out.println(test);

I have printed both out to see what is wrong. The results are as follows:

[REAL* (61.739814266023316, 40.25177570831545, 36.09450830843867, 48.06821029847672,...etc)]
[D@61de33

The problem is how R returns the results to java; it tells java what x is, if they were strings it would say [String*(..whatever..)]. I just want what is in the bracket. Also the line it returns is a string regardless.

I will be working with large data so I want it to be fast. I had tried to use subsets, extracting what is in the brackets and then parsing them to doubles but there must be a better solution. Also that doesn't seem to work for data with more than 100 points.


回答1:


Since there's already a reference to this question, let here be an answer:

System.out.println(test); where test is double[] literally means System.out.println(test.toString());

The problem is, in Java, arrays have got a very poor implementation of toString(). Hence, in order to get the result you need, you need to use

REXP x;
x = re.eval("rnorm(100,50,10)");
double[] test = x.asDoubleArray();
System.out.println(x);
System.out.println(Arrays.asList(test)); // note we get an array-backed list here

as lists have proper toString() method.

Again, my apologies for an obvious answer.



来源:https://stackoverflow.com/questions/7471689/converting-rexp-object-to-a-double-array-java-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!