如何在collapse::collap中加入条件实现指定分组聚合逻辑?
使用collapse::collap实现指定分组聚合逻辑
聚合需求
对数据集按id分组,执行以下聚合规则:
type、colour:取组内第一个值x1、x2:取组内最后一个值test_date:优先选取组内result为"positive"的首个日期;若组内无positive结果,则选取result为"negative"的最后一个日期
解决方案:单次调用collap实现
通过在collap的custom参数中添加自定义聚合函数,结合custom.args传递辅助字段,可一次性完成所有聚合逻辑:
library(collapse) set.seed(1) df <- data.frame(id = rep(letters[1:3], each = 3), result = c("negative", "positive", "positive", "negative", "negative", "negative", "positive", "negative", "positive"), test_date = seq.Date(from = as.Date("01/01/1998", "%d/%m/%Y"), to = as.Date("09/01/1998", "%d/%m/%Y"), by = "day"), type = c("car", "truck", "bike", "wheel", "tyre", "lorry", "car", "bike", "wheel"), colour = c("gre", "blu", "re", "dblu", "yel", "re", "ora", "ti", "bla"), x1 = sample(letters, 9), x2 = sample(letters, 9)) # 定义处理test_date的自定义聚合函数 get_test_date <- function(date, result) { pos_dates <- date[result == "positive"] if (length(pos_dates) > 0) { collapse::first(pos_dates) } else { collapse::last(date[result == "negative"]) } } # 单次调用collap完成所有聚合 out_collap <- collap(df, ~ id, custom = list( ffirst = c("type", "colour"), # 取首个值 flast = c("x1", "x2"), # 取最后一个值 test_date = get_test_date # 自定义处理test_date ), # 传递自定义函数需要的额外字段result custom.args = list(result = df$result)) # 查看结果 out_collap
输出结果
运行后得到与dplyr版本完全一致的结果:
id type colour x1 x2 test_date 1 a car gre g j 1998-01-02 2 b wheel dblu k x 1998-01-06 3 c car ora w o 1998-01-07
关键说明
custom参数支持混合使用collapse内置聚合函数(如ffirst、flast)和自定义函数,灵活处理不同字段的聚合规则custom.args用于传递自定义聚合函数所需的额外列数据(此处为result,用于判断日期筛选条件)- 自定义函数中使用
collapse::first和collapse::last而非base R函数,能更好地兼容collapse的分组计算逻辑,提升效率
内容的提问来源于stack exchange,提问作者user63230
相关产品推荐
相关产品推荐

