Search code examples
rarraylistjri

RVector/REXP to ArrayList


I'm having some trouble with the JRI-Package. Basically I'm programming in Java and I access a SQL-Database through R with RJDBC. Anyway, my problem is more of a R/JRI-Problem than anything else, I just don't want you to be confused.

My Code:

RVector result_a = re.eval("dbGetQuery(conn, \"select movies_id from movies\")").asVector();
REXP result_b = re.eval("dbGetQuery(conn, \"select movies_id from movies\")");
System.out.println(result_a.firstElement());
List<Object> S = Arrays.asList(result_a.get(0));
for(int i = 0; i < S.size(); i++) {
    System.out.println("Nr. " + i + ": " + S.get(i));
}
System.out.println(result_b.getContent());

Output:

[REAL* (1.0, 2.0, 3.0, 4.0, 5.0)]
Nr. 0: [REAL* (1.0, 2.0, 3.0, 4.0, 5.0)]
[[REAL* (1.0, 2.0, 3.0, 4.0, 5.0)]]

The thing is, that for some reason the Objects REXP (and also RVector, though not shown) are covered in double brackets (when being printed). I suppose, it is an vector in a vector? And the actual problem: The data is compressed in one single place, I want it to be like this:

Nr. 0: 1.0
Nr. 1: 2.0
Nr. 2: 3.0
Nr. 3: 4.0
Nr. 4: 5.0

I tried out all the functions I could use, but nothing seems to work. It's always spit out as a single String or Object or whatever and I can't really pinpoint the problem.

I appreciate any hint. :)


Solution

  • The output of dbGetQuery is a data.frame which is a list. In the case of your query, it is a list of length one. You should take the first element of that list, which is a vector, and from it the single elements you want to display. Try something like:

      double[] result_a = re.eval("dbGetQuery(conn, \"select movies_id from movies\")").asList().at(0).asDoubleArray();  
    

    In this way, result_a should be a regular java double array and you can print its values.