How can I get an index vector in rpy2, or if that doesn't exist, how can I select two columns?

StackOverflow https://stackoverflow.com/questions/9435004

  •  12-11-2019
  •  | 
  •  

Question

I want to do the same thing as in the R example found here: http://www.r-tutor.com/r-introduction/data-frame/data-frame-column-slice. He makes use of the mtcars datase which looks like this:

               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ...

And then selects the mpg and hp column with an index vector

> mtcars[c("mpg", "hp")] 
                   mpg  hp 
Mazda RX4         21.0 110 
Mazda RX4 Wag     21.0 110 
Datsun 710        22.8  93 

It's simple to retrieve one row in rpy2, to get mpg in this case:

import rpy2.robjects as R
R.r['mtcars'][0]

However, I don't know how to select two columns

import rpy2.robjects as R
R.r['mtcars'][R.vectors.IntVector([0,3])]

Gives

TypeError: 'IntVector' object cannot be interpreted as an index

Just like every other vector that is in R.vectors (I tried them all)

So my question comes down to, how can I get an index vector in rpy2, or if that doesn't exist, how can I select two columns?

Thanks!

Was it helpful?

Solution

Answered on the rpy mailing list. Use the rx/rx2 to extract element the R-way (note that indexing starts at one in R).

import rpy2.robjects as R
R.r['mtcars'].rx[R.vectors.IntVector([0,3]).ro + 1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top