如何以编程方式在data.table中选择列? [英] How to select columns programmatically in a data.table?
问题描述
我有以下data.table(DT):
I have the following data.table (DT):
DT <- data.table(V1 = 1:3, V2 = 4:6, V3 = 7:9)
我想选择一个子集通过使用存储相关变量名称的对象以编程方式(动态)对变量进行编程。例如,我要选择存储在变量 keep中的两列 V1和 V3
I would like to select a subset of the variables programmatically (dynamically), by using an object where the relevant variable names are stored. For example, I want to select the two columns "V1" and "V3" stored in a variable "keep"
keep <- c("V1", "V3")
如果我们选择保留 data.frame中的列,则可以使用以下内容:
If we were to select the "keep" columns from a data.frame, the following would work:
DT[keep]
不幸的是,当这是一个data.table时,这不起作用。我以为data.frame和data.table与这种行为相同,但是显然它们不是。有人能够建议正确的语法吗?
Unfortunately, this is not working when this is a data.table. I thought the data.frame and data.table are identical with this kind of behavior, but apperently they aren't. Anybody able to advise on the correct syntax?
推荐答案
有些可能性:
DT[, keep, with = FALSE]
DT[, c('V1', 'V3'), with = FALSE]
DT[, c(1, 3), with = FALSE]
DT[, list(V1, V3)]
DF [c('V1','V3')]
起作用的原因 data.frame
是否包含在中?`[.data.frame`
The reason DF[c('V1','V3')]
works as it does for a data.frame
is covered in ?`[.data.frame`
数据帧可以用几种模式索引。当使用
[
和[[
时,
具有单个向量索引(x [i]
或x [[i]]
),它们对数据框
进行索引,就好像它是一个列表一样。在这种用法中,将忽略drop
参数,并带有
警告。
Data frames can be indexed in several modes. When
[
and[[
are used with a single vector index (x[i]
orx[[i]]
), they index the data frame as if it were a list. In this usage adrop
argument is ignored, with a warning.
来自 data.table 1.10.2
,则可以使用。 。
以编程方式子集化列的前缀:
From data.table 1.10.2
, you may use the ..
prefix when subsetting columns programmatically:
当
j
是前缀为的符号。
它将在调用范围中查找,其值将用作列名或数字[...]这是实验性的。 p>
When
j
is a symbol prefixed with..
it will be looked up in calling scope and its value taken to be column names or numbers [...] It is experimental.
因此:
DT[ , ..keep]
# V1 V3
# 1: 1 7
# 2: 2 8
# 3: 3 9
这篇关于如何以编程方式在data.table中选择列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!