【问题标题】:Grouping Customer Sessions by Customer and Time until Next Transaction按客户和时间对客户会话进行分组,直到下一次交易
【发布时间】: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))

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:
    library(dplyr)
    cust_transactions_before %>% 
      group_by(customer_name) %>% 
      mutate(cust_session = cumsum(lag(time_until_next, default = 31) > 30))
    
       customer_name time_until_next cust_session
       <chr>                   <dbl>        <int>
     1 a                          41            1
     2 a                          19            2
     3 a                           5            2
     4 a                          27            2
     5 a                          49            2
     6 a                           3            3
     7 a                          10            3
     8 a                          20            3
     9 a                          13            3
    10 a                          NA            3
    11 b                          25            1
    12 b                          17            1
    13 b                           8            1
    14 b                          33            1
    15 b                          25            2
    16 b                          31            2
    17 b                          19            3
    18 b                           5            3
    19 b                          27            3
    20 b                          NA            3
    

    【讨论】:

      【解决方案2】:

      在 dplyr 1.1.0 中,我们可以使用:

      cust_transactions_before |>
        mutate(cust_session = consecutive_id(time_until_next > 30), .by = customer_name)
      

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 1970-01-01
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2019-05-05
        相关资源
        最近更新 更多