【问题标题】:Count consecutive prior dates per group计算每组连续的先前日期
【发布时间】:2020-03-04 14:11:21
【问题描述】:

我的示例 data.frame(日期格式 d/m/y),记录客户活跃的日期:

customer    date 
1           10/1/20
1           9/1/20 
1           6/1/20
2           10/1/20
2           8/1/20
2           7/1/20
2           6/1/20

我想像这样创建一个列“n_consecutive_days”:

customer    date    n_consecutive_days
1           10/1/20  2
1           9/1/20   1
1           6/1/20   N/A
2           10/1/20  1
2           8/1/20   3
2           7/1/20   2
2           6/1/20   N/A

新列计算每个客户之前连续日期的数量。我希望客户的第一个日期是 N/A,因为如果它是第一个日期,那么谈论前连续几天是没有意义的。

任何帮助将不胜感激。我可以计算日期之间的差异,但不能根据需要计算连续天数。

【问题讨论】:

  • 为什么在你想要的输出中多了一行?
  • 我不太明白应该如何计算 n_consecutive_days 列...N/A0 之间有什么区别?为什么没有1的条目?
  • @AaronMontgomery,看起来是日期格式"%e/%m/%y",但如果没有 OP 的确认,我无法 100% 确定
  • @Andrew 这很有可能——但我仍然对为什么使用N/A 以及为什么不使用1 感到困惑......
  • 这很容易做到。将其设置为 0 或 1 以表示孤独的一天,无论是什么更容易编码。然后在最后将其更改为您想要的任何内容(1 -> 00 -> 1)。没什么大不了的。

标签: r dataframe dplyr


【解决方案1】:

一种方法是:

library(dplyr)

df %>%
  group_by(customer, idx = cumsum(as.integer(c(0, diff(as.Date(date, '%d/%m/%y')))) != -1)) %>%
  mutate(n_consecutive_days = rev(sequence(n()))) %>% ungroup() %>%
  group_by(customer) %>%
  mutate(n_consecutive_days = replace(n_consecutive_days, row_number() == n(), NA), idx = NULL)

输出:

# A tibble: 7 x 3
# Groups:   customer [2]
  customer date    n_consecutive_days
     <int> <fct>                <int>
1        1 10/1/20                  2
2        1 9/1/20                   1
3        1 6/1/20                  NA
4        2 10/1/20                  1
5        2 8/1/20                   3
6        2 7/1/20                   2
7        2 6/1/20                  NA

【讨论】:

    【解决方案2】:

    使用data.table的选项:

    #ensure that data is sorted by customer and reverse chronological
    setorder(DT, customer, -date)
    
    #group by customer and consecutive dates and then create the sequence
    DT[, ncd := .N:1L, .(customer, cumsum(c(0L, diff(date)!=-1L)))]
    
    #set the first date in each customer to NA
    DT[DT[, .I[.N], customer]$V1, ncd := NA]
    

    输出:

       customer       date ncd
    1:        1 2020-01-10   2
    2:        1 2020-01-09   1
    3:        1 2020-01-06  NA
    4:        2 2020-01-10   1
    5:        2 2020-01-08   3
    6:        2 2020-01-07   2
    7:        2 2020-01-06  NA
    

    数据:

    library(data.table)
    DT <- fread("customer    date 
    1           10/1/20
    1           9/1/20 
    1           6/1/20
    2           10/1/20
    2           8/1/20
    2           7/1/20
    2           6/1/20")
    DT[, date := as.IDate(date, format="%d/%m/%y")]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2023-01-17
      • 1970-01-01
      • 2019-05-11
      相关资源
      最近更新 更多