R顺序计数列 数据

问题描述

    set.seed(0)
data = data.frame(ID = 1:1000,X1=runif(1000),X2=runif(1000),DROP1=sample(0:1,r=T),DROP2=sample(0:1,DROP3=sample(0:1,r=T))

说这是我的数据。我希望这样做:计算等于1的DROP1的值数量;然后在DROP1等于1的情况下计算DROP2的值数;然后在DROP2等于1且DROP1等于1的情况下,计算DROP3的值等于1。我可以手动执行此操作,但实际数据文件很大,并且具有80多个DROP变量。理想的输出只是看起来如下的打印输出

DROP1,#
DROP2 (AFTER DROP1),#
DROP3 (AFTER DROP1 & DROP2),#

解决方法

这是base R的一个选项,其中我们使用grep获得'DROP'列名('nm1')。然后遍历那些序列,获得其中的seq,将数据列作为子集,使用Reduce获得带有&的逻辑向量(如果我们具有所有具有1代表一行,即1 => TRUE,0 => FALSE),然后获取这些元素的sum以返回计数

nm1 <- grep('^DROP',names(data),value = TRUE)
sapply(seq_along(nm1),function(i)  {i1 <- seq(i)
        sum(Reduce(`&`,data[nm1[i1]])) })
#[1] 503 249 137

或与data.table

library(data.table)
setDT(data)
lapply(seq_along(nm1),function(i) {
         i1 <- seq(i)
         data[,sum(Reduce(`&`,.SD)),.SDcols = nm1[i1]]

    })

数据

set.seed(0)
data <- data.frame(ID = 1:1000,X1=runif(1000),X2=runif(1000),DROP1=sample(0:1,1000,replace = TRUE),DROP2=sample(0:1,DROP3=sample(0:1,replace = TRUE))
,

另一种选择:

set.seed(0)
data = data.frame(ID = 1:1000,r=T),r=T))

tb <- table(data[,4:6])
tb
#,DROP3 = 0
#      DROP2
# DROP1   0   1
#     0 108 126
#     1 118 112
#,DROP3 = 1
#      DROP2
# DROP1   0   1
#     0 128 135
#     1 136 137
sum(tb[2,])
# [1] 503
sum(tb[2,2,])
# [1] 249
sum(tb[2,2])
# [1] 137

证明,体力劳动

sum(with(data,DROP1 == 1L))
# [1] 503
sum(with(data,DROP1 == 1L & DROP2 == 1L))
# [1] 249
sum(with(data,DROP1 == 1L & DROP2 == 1L & DROP3 == 1L))
# [1] 137