首页 > 解决方案 > r 数据框检查下 n 个变量

问题描述

我有一个如下的数据框,其中 x 是一个布尔列

id    |        p    |     q
------+-------------+----------
 1    |        1    |     n
 1    |        0    |     y     
 1    |        0    |     y
 2    |        0    |     n
 2    |        1    |     y
 2    |        0    |     n
 2    |        0    |     y 
 3    |        0    |     n
 3    |        1    |     y
 3    |        0    |     n
 3    |        0    |     n

我有一个变量 n。如果 p 为 1,我想检查在接下来的 n 行(属于同一 id)中,列 q 的值是否为 y。如果是,我想创建一个新列 r,其中该列的值为 y,否则为 n。如果 p 不是 1,默认情况下 r 将为空。如下(假设是 2 为例)

id    |        p    |     q    |     r
------+-------------+----------+----------
 1    |        1    |     n    |     y
 1    |        0    |     y    |     -
 1    |        0    |     y    |     -
 2    |        0    |     n    |     -
 2    |        1    |     y    |     y
 2    |        0    |     n    |     -
 2    |        0    |     y    |     -
 3    |        0    |     n    |     -
 3    |        1    |     y    |     n
 3    |        0    |     n    |     -
 3    |        0    |     n    |     -

可以使用铅功能吗?(我可以动态设置要检查的行数)

标签: rdataframe

解决方案


我将使用 {data.table} 提供一种可能的解决方案。

library(data.table)

DT <- data.table(id = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),
                 p = c(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0),
                 q = c("n", "y", "y", "n", "y", "n", "y", "n", "y", "n", "n"))

# Here DT2 is another data.table containing only cases where p is 0
# I will use this to see if there are any "y" in column "q"
DT2 <- DT[p == 0, ]
DT2 <- DT2[, .(r = paste0(q, collapse = "")), by = id]
DT2[, r := ifelse(grepl("y", r), "y", "n")]

# Then I will join the tables together
setkey(DT, id)
setkey(DT2, id)

# And remove the values of column "r" when column "p" has value of 0 
DT <- DT[DT2]
DT[p == 0, r := NA]

推荐阅读