.SD列上的data.table子集条件?

时间:2019-09-24 17:35:41

标签: r data.table

我想创建与下面的最小可重复示例相同的结果,但是您可以看到最后一个代码的子设置条件基本上是删除.SD列不应全零的行。 / p>

library(dplyr)

library(data.table)

set.seed(1)

t1 <- sample(-1:1, 999999, replace = T) %>% matrix(ncol = 9) %>% as.data.table %>% {cbind.data.frame(id = 1:nrow(.), .)}

t1[V1 != 0|V2 != 0|V3 != 0|V4 != 0|V5 != 0|V6 != 0|V7 != 0|V8 != 0|V9 != 0, lapply(.SD, sum), by = id]

我尝试过

t1[sum(abs(.SD)) != 0, lapply(.SD, sum), by = id]

2 个答案:

答案 0 :(得分:2)

我们可以使用i创建Reduce

i1 <- t1[, .I[Reduce(`|`, lapply(.SD, `!=`, 0))], .SDcols = V1: V9]
out2 <- t1[i1, lapply(.SD, sum), by = id]

-检查OP的输出

out1 <- t1[V1 != 0|V2 != 0|V3 != 0|V4 != 0|V5 != 0|V6 != 0|V7 != 0|V8 != 0|V9 != 0, lapply(.SD, sum), by = id]  
identical(out1, out2)
#[1] TRUE

答案 1 :(得分:1)

使用https://www.googleapis.com/gmail/v1/users/me/messages?maxresults=5&q=from:mysender@mydomain.com

rowSums()