【发布时间】:2023-02-09 01:17:11
【问题描述】:
我需要按时间对客户购物会话进行分类,直到下一次交易为止。一个示例数据框是:
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_))
我想按 customer_name 分组,并让每个客户的第一笔交易从 1 开始,值 cust_session。对于下一次观察,我想做一个 if/then,如果 time_until_next 是 <= 30,那么保持与之前观察相同的 cust_session 会话号。如果 time_until_next 大于 30,则取前一个 cust_session 并向其加 1。
最后,如果 time_until_next 是 NA,那么让它等于之前的 cust_session。
处理后成功的数据框如下所示:
cust_transactions_after <-
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_session = c(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3))
【问题讨论】: