[R] Transfer String Array from R to java

Simon Urbanek simon.urbanek at r-project.org
Fri Dec 2 00:23:14 CET 2005


Vasu,

On Dec 1, 2005, at 5:20 PM, Vasundhara Akkineni wrote:

> i want to extract the first column of names as a matrix and pass it  
> to a String[] type in java. I am using RServe and was able to pass  
> the other two columns to double[] in java but was not able to do so  
> for data[,1] to a String[]. I have to do this in order to access  
> induvidual string names.

It pretty much depends on what the column really is. An answer  
upfront: there is currently no String[] construct.

Let's illustrate the details on an example:

REXP x=c.eval("data(iris); as.character(iris$Species)");

What you get is a Vector of REXPs that are Strings, so to construct  
String[] you could do the following:

Vector v=x.asVector();
String s[] = new String[v.size()];
int i=0;
while (i<s.length) { s[i]=((REXP)v.elementAt(i)).asString(); i++; };

Now, if you fetch the factor directly, then you get RFactor:

REXP x=c.eval("data(iris); iris$Species");
RFactor f=x.asFactor();

Unfortunately RFactor is not very helpful, I have to admit. The idea  
was to have a flexible structure that holds both the indices and the  
level names. But the implementation fails to declare both Vectors id  
and val public, so you can't get to them. If you fix that, then you  
can use the above to fetch the levels and the indices, but that's  
very clumsy. I'll fix the RFactor class and in the meantime you can  
get the components separately like this:

REXP x = c.eval("unclass(iris$Species)");
int indices[] = x.asIntArray();
Vector v = x.getAttribute().asList().getHead().asVector();
// v is the vector containing the levels, so use above code to create  
String[] from it

I agree that this is all clumsy and I should add direct support for  
String[] in the same fashion that int[] and double[] are handled...  
I'm putting it on my ToDo list to be fixed soon...

Cheers,
Simon




More information about the R-help mailing list