r - 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 | -
可以使用铅功能吗?(我可以动态设置要检查的行数)
解决方案
我将使用 {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]
推荐阅读
- google-cloud-platform - Stackdriver 帐户可以监控 GCP 中不同组织中的资源吗?
- git - 从 Jenkinsfile 中获取有关其他分支的信息
- c# - Console.WriteLine 不工作
- c++ - 使用整数向量的邻接矩阵的内存节省替代方案
- haskell - Haskell - 作为函数的输入
- java - 如果大部分方法都是调用站点的死代码,java可以内联一个大方法吗?
- swift - 使用按钮和文本字段打开链接
- azure - 验证 Azure 资源组选项从 VS2017 的菜单中消失
- python - 下载 Anaconda Navigator 后无法从 Spyder 打开 .py 文件
- yii2 - 如何通过 PostSearchModel 搜索具有两个或多个特定标签的帖子?