简体   繁体   English

您可以使用 .SDcols 对 data.table 中的行进行子集化吗

[英]Can you use .SDcols to subset rows in data.table

Is there a way to use .SDcols in datatable to select rows.有没有办法在数据表中使用 .SDcols 来选择行。 For example, in mtcars, select rows where vs, am and carb all equal 1. I have a lot of columns and want to avoid a lot of typing.例如,在 mtcars 中,选择 vs、am 和 carb 都等于 1 的行。我有很多列,希望避免大量输入。

I know this does not work我知道这行不通

 mtcars[ lapply( .SD == 1),  , .SDcols = c('vs, 'am', 'carb')]

We may need Reduce to return a single logical vector and use that as index for subsetting我们可能需要Reduce返回单个逻辑向量并将其用作子集的索引

library(data.table)
mtcars[mtcars[, Reduce(`&`, lapply( .SD, `==`,  1)), 
         .SDcols = c('vs', 'am', 'carb')]]

-output -输出

    mpg cyl  disp hp drat    wt  qsec vs am gear carb
1: 22.8   4 108.0 93 3.85 2.320 18.61  1  1    4    1
2: 32.4   4  78.7 66 4.08 2.200 19.47  1  1    4    1
3: 33.9   4  71.1 65 4.22 1.835 19.90  1  1    4    1
4: 27.3   4  79.0 66 4.08 1.935 18.90  1  1    4    1

Or use rowSums to create the logical vector或者使用rowSums创建逻辑向量

mtcars[mtcars[, .I[rowSums(.SD == 1) == 3], .SDcols = c('vs', 'am', 'carb') ]]

data数据

mtcars <- as.data.table(mtcars)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM