data.table 中的 Select 列基于逻辑向量

Select columns in data.table based on logical vector

假设我有以下 data.frame 和以下 data.table:

DF = data.frame(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)

使用 data.frame,我可以 select 基于逻辑向量的列,如下所示:

DF[,c(TRUE,TRUE,FALSE)]

结果是:

  x y
1 a 1
2 a 3
3 a 6
4 b 1
5 b 3
6 b 6
7 c 1
8 c 3
9 c 6

但是

DT[,c(TRUE,TRUE,FALSE)]

导致:

[1]  TRUE  TRUE FALSE

如何做到?

更新时间 2020-04-22

data.table 的当前 CRAN 版本中,DT[ , c(TRUE, TRUE, FALSE)] 可以工作——不需要 with=FALSE。为后代留下这个较旧的答案:


我们需要with=FALSE

DT[, c(TRUE, TRUE, FALSE), with=FALSE]

基于 ?data.table

中的文档

By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. When with=FALSE j is a character vector of column names or a numeric vector of column positions to select, and the value returned is always a data.table. with=FALSE is often useful in data.table to select columns dynamically.