如何使用某些列名的字符向量选择data.table中的列? [英] How to select columns in data.table using a character vector of certain column names?

查看:72
本文介绍了如何使用某些列名的字符向量选择data.table中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在data.table中选择其名称出现在我的字符向量中的那些列。该操作只能在纯data.frame中使用,而不能在data.table中使用。这是一个可复制的示例。

I am trying to select those columns in a data.table whose name appears in my character vector. The operation works in a pure data.frame, but doesn't work in a data.table. Here's a reproducible example.

> names(mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
> myVector <- c('disp', 'hp', 'wt')
> head(mtcars[, myVector])
                  disp  hp    wt
Mazda RX4          160 110 2.620
Mazda RX4 Wag      160 110 2.875
Datsun 710         108  93 2.320
Hornet 4 Drive     258 110 3.215
Hornet Sportabout  360 175 3.440
Valiant            225 105 3.460

I刚刚制作了一个包含 disp hp wt ,然后使用该向量在data.frame中选择了相应的列。现在,从我的data.frame中创建一个data.table对象,并尝试执行相同的操作。

I just made a vector which includes disp, hp, and wt and I selected the corresponding columns in my data.frame using that vector. Let's now make a data.table object from my data.frame and try to do the same operation.

> library(data.table)
> mtcarsDT <- data.table(mtcars)
> mtcarsDT[, myVector]
[1] "disp" "hp"   "wt"  


推荐答案

我们可以使用 .. 表示法找到 myVector 作为列的向量位置,就像它将在 data.frame

We can use .. notation to find myVector as a vector of column positions, like it would work in data.frame

mtcarsDT[, ..myVector]

根据?data.table


如果数据集内部和父范围中的变量名称重叠,则可以使用双点前缀。 cols 明确引用'cols变量父作用域,而不是从您的数据集中。

In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset.

这篇关于如何使用某些列名的字符向量选择data.table中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆