You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 14:22:42