r - 以 Group By 方式标记行
问题描述
我想区分 3 种情况:
1 - Events A and B happened at the same session ("ID") - "flag 1".
2 - Events B happened without A - "flag 2".
3 - Else - "flag 0".
例如:
ID EVENT
1 A
1 B
2 D
2 E
2 C
3 B
4 A
我想得到:
ID FLAG
1 1
2 0
3 2
4 0
解决方案
可用于dplyr::case_when
汇总 ID 的值。在这种情况下,使用any
andall
将有助于确定汇总数据是否同时包含A
andB
或仅包含B
。解决方案如下:
library(dplyr)
# In addition, "plyr" shouldn't be brought to the session, otherwise
# it will return one line
df %>% group_by(ID) %>%
summarise(FLAG = case_when(
any(EVENT == "A") & any(EVENT == "B") ~ 1,
all(EVENT == "B") ~ 2,
TRUE ~ 0
)) %>% as.data.frame()
# ID FLAG
# 1 1 1
# 2 2 0
# 3 3 2
# 4 4 0
数据:
df <- read.table(text=
"ID EVENT
1 A
1 B
2 D
2 c
3 B
4 A",
header = TRUE, stringsAsFactors = FALSE)
推荐阅读
- mysql - 优化 mysql 请求:内部连接很长
- ios - 为 mac 催化剂的 info.plist 文件中的键设置不同的值
- amazon-web-services - 如何配置 Spark / Glue 以避免在 Glue 作业成功执行后创建空的 $_folder_$
- c# - 备份和重新加载控制台命令历史
- c# - 在深色模式下保存并在浅色模式下打开时 UWP RichEditBox 文本颜色问题
- forms - 微软表单识别器 2.1
- javascript - 使用useState挂钩时,在React中提交表单时禁用提交按钮无法按预期工作
- javascript - 在重新渲染期间保持 React Portal 显示在外部窗口上
- office-js - 回调函数未正确执行 - Outlook 加载项
- java - 如何同时调用相同的 AWS Lambda 函数?