【问题标题】:R Count Sequentially ColumnsR按顺序计数列
【发布时间】:2020-10-23 22:40:40
【问题描述】:
    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,r=T),DROP3=sample(0:1,r=T))

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

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

【问题讨论】:

  • @akrun 我觉得你可能有一个聪明的 data.table 解决方案!
  • 很好奇,当我运行您的示例时,所有 drop2/drop3 列都是 0

标签: r data.table inclusion


【解决方案1】:

这是一个带有base R 的选项,我们使用grep 获取“DROP”列名(“nm1”)。然后遍历这些序列,获取其中的seq,对数据列进行子集化,使用Reduce 获取带有& 的逻辑向量(仅当我们的所有列都为一行时才为真,即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,1000, replace = TRUE),
           DROP3=sample(0:1,1000,replace = TRUE))

【讨论】:

    【解决方案2】:

    另一种选择:

    set.seed(0)
    data = data.frame(ID = 1:1000, X1=runif(1000), X2=runif(1000), DROP1=sample(0:1,1000,r=T),DROP2=sample(0:1,1000,r=T),DROP3=sample(0:1,1000,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,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      相关资源
      最近更新 更多