3

我想做与此处的 R 示例相同的事情:http ://www.r-tutor.com/r-introduction/data-frame/data-frame-column-slice 。他使用 mtcars 数据集,如下所示:

               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 ...

然后选择带有索引向量的 mpg 和 hp 列

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

在 rpy2 中检索一行很简单,在这种情况下获取 mpg:

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

但是,我不知道如何选择两列

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

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

就像 R.vectors 中的所有其他向量一样(我都试过了)

所以我的问题归结为,如何在 rpy2 中获取索引向量,或者如果不存在,我如何选择两列?

谢谢!

4

1 回答 1

3

在 rpy 邮件列表上回答。使用 rx/rx2 以 R 方式提取元素(请注意,索引从 R 中的 1 开始)。

import rpy2.robjects as R
R.r['mtcars'].rx[R.vectors.IntVector([0,3]).ro + 1]
于 2012-02-29T08:49:28.557 回答