首页 > 解决方案 > R - 计算最大连续日期数

问题描述

我正在尝试按组计算连续日期的最大长度,但我很难得到它。我已经为我的类似布局的小标题包含了代码。

library(dplyr)

# construct sample tibble:
df <- tibble(
  key = rep(1:2, c(6,4)),
  Date = c(seq(as.Date('2016-12-17'), as.Date('2016-12-19'), '1 day'),
           seq(as.Date('2016-12-21'), as.Date('2016-12-23'), '1 day'),
           seq(as.Date('2017-05-18'), as.Date('2017-05-21'), '1 day'))          
)

我尝试使用lag()添加标签 ( 1) 来指示日期之间何时存在间隔,然后0使用 计算列中的最大长度rle,但这不适用于所有可能的连续日期和间隔的配置keys

有没有办法按组返回最大连续日期数?

标签: rdataframedplyrtibble

解决方案


给定一个向量,让我们首先创建一个函数来查找最大连续天数:

gl <- function(x) {
  y <- c(unclass(diff(x)))  # c and unclass -- preparing it for rle
  r <- rle(y)
  with(r, max(lengths[values==1]))
}

现在我们可以按照通常的 dplyrry 方式使用它:

df %>% group_by(key) %>% summarise(max.consecutive = gl(Date))

#  A tibble: 2 x 2
#     key max.consecutive
#   <int>           <int>
# 1     1               2
# 2     2               3

推荐阅读