如何按客户及下次交易间隔时间对客户购物会话分组?
按交易间隔对客户购物会话分桶的实现方案
要实现按客户分组的购物会话分桶,规则如下:
- 每个客户的首笔交易会话编号从1开始
- 后续交易:
- 若上一笔交易的
time_until_next> 30,新会话编号 = 上一会话编号 + 1 - 若上一笔交易的
time_until_next≤ 30 或为NA,会话编号与上一笔保持一致
- 若上一笔交易的
直接用tidyverse工具链就能搞定,代码如下:
library(tidyverse) # 原始数据 cust_transactions_before <- tibble( customer_name = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"), time_until_next = c(41, 19, 5, 27, 49, 3, 10, 20, 13, NA_integer_, 25, 17, 8, 33, 25, 31, 19, 5, 27, NA_integer_) ) # 处理会话分桶 cust_transactions_after <- cust_transactions_before %>% group_by(customer_name) %>% mutate( # 标记需要开启新会话的位置:首条记录必为1,后续仅上一条间隔>30时标记1 session_flag = case_when( row_number() == 1 ~ 1L, lag(time_until_next) > 30 ~ 1L, TRUE ~ 0L ), # 累加标记得到连续的会话编号 cust_session = cumsum(session_flag) ) %>% select(-session_flag) %>% # 清理中间变量 ungroup() # 查看结果 cust_transactions_after
代码解释
- 分组处理:用
group_by(customer_name)确保每个客户的会话独立计算 - 会话切换标记:
session_flag变量专门标记何时需要开启新会话,首条记录强制为1(初始化会话),后续只在上一笔交易间隔超过30时标记为1 - 生成会话编号:通过
cumsum(session_flag)对标记累加,自然得到连续的会话编号 - 清理收尾:移除中间变量并取消分组,得到符合要求的最终数据框
运行这段代码后,输出结果完全匹配目标数据框。
内容的提问来源于stack exchange,提问作者Frank B.
相关产品推荐
相关产品推荐

