如何对含重复分组变量的数据框按用户目标进度分类汇总?
问题描述
现有R语言数据框df1:
df1<- structure(list(Type.of.Goal = c("Nutrition/Hydration Goal", "Nutrition/Hydration Goal", "Fitness Goal", "Fitness Goal", "Lifestyle Goal", "Fitness Goal", "Lifestyle Goal", "Fitness Goal", "Nutrition/Hydration Goal", "Nutrition/Hydration Goal", "Nutrition/Hydration Goal", "Lifestyle Goal", "Lifestyle Goal", "Lifestyle Goal", "Nutrition/Hydration Goal", "Lifestyle Goal", "Fitness Goal", "Fitness Goal", "Lifestyle Goal", "Lifestyle Goal", "Fitness Goal", "Lifestyle Goal", "Lifestyle Goal" ), progress_made = c(1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1), id = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "c", "d", "d", "d", "e", "e", "e", "e", "f", "f", "f", "g", "g", "g")), row.names = c(734L, 736L, 737L, 964L, 965L, 966L, 1446L, 1447L, 1448L, 1449L, 1485L, 1486L, 1487L, 1553L, 1554L, 1555L, 1556L, 1918L, 1919L, 1920L, 1952L, 1953L, 1954L ), class = "data.frame")
其中progress_made为1表示该目标有进展,0表示无进展。需按id分组,将每个用户归为以下三类之一:
- 所有设定的目标均有进展
- 部分目标有进展、部分无进展
- 所有目标均无进展
期望得到的结果数据框如下:
df_results<- data.frame(id= c("a", "b", "c", "d", "e", "f", "g"), results= c("All goals saw progress", "No goals saw progress", "Some goals saw progress, but not all", "Some goals saw progress, but not all", "Some goals saw progress, but not all", "All goals saw progress", "All goals saw progress"))
此前尝试将数据框转为宽表(以id和Type.of.Goal为列,progress_made为值),结合rowSums、mutate和ifelse实现分类,但当同一用户同一目标类型存在多个条目时该方法失效,现寻求可行解决方案。
解决方案
核心思路是直接按用户分组,通过判断用户的目标进展分布完成分类,无需转宽表,同时可根据业务需求选择是否对同一用户的重复目标去重。
方式一:基于所有目标条目判断
如果无需对同一用户的重复目标去重,直接基于所有条目判断用户的整体进展情况:
library(dplyr) df_results <- df1 %>% group_by(id) %>% summarise( has_progress = any(progress_made == 1), has_no_progress = any(progress_made == 0), .groups = "drop" ) %>% mutate( results = case_when( !has_progress ~ "No goals saw progress", !has_no_progress ~ "All goals saw progress", TRUE ~ "Some goals saw progress, but not all" ) ) %>% select(id, results)
方式二:先去重同一用户的重复目标
如果同一用户的同一目标存在多条记录,先按id和Type.of.Goal分组,确定每个目标的最终进展状态(这里以“只要该目标有过进展就算有”为例,用max()取状态),再判断用户的整体情况:
library(dplyr) df_results <- df1 %>% # 按用户和目标分组,确定每个目标的进展状态 group_by(id, Type.of.Goal) %>% summarise(goal_progress = max(progress_made), .groups = "drop_last") %>% # 按用户分组,判断整体进展类别 summarise( all_progress = all(goal_progress == 1), no_progress = all(goal_progress == 0), .groups = "drop" ) %>% mutate( results = case_when( no_progress ~ "No goals saw progress", all_progress ~ "All goals saw progress", TRUE ~ "Some goals saw progress, but not all" ) ) %>% select(id, results)
运行上述任意一种方式的代码,均可得到符合要求的结果数据框,可根据实际业务逻辑选择对应方式。
内容的提问来源于stack exchange,提问作者pww_qs
相关产品推荐
相关产品推荐

