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

查看:14
本文介绍了如何使用某些列名的字符向量选择 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

我刚刚制作了一个包含 disphpwt 的向量,并使用它在我的 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天全站免登陆