r - 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
。
有没有办法按组返回最大连续日期数?
解决方案
给定一个向量,让我们首先创建一个函数来查找最大连续天数:
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
推荐阅读
- python-3.x - Graphviz 左对齐边缘标签文本
- angular - 计算 ts / angular 中字符串变量的小时差
- go - 如何使用 bash 的括号扩展语法创建目录树
- database - prisma 模式中的一对多自关系
- javascript - 如何从 Firebase 中的 batch.commit() 计划函数返回一个承诺
- javascript - Javascript - 加载时选择元素
- python - 为什么我收到一个错误,显示模块“多处理”没有属性“sharedctypes”?
- express - 异步等待句柄 Promise {
} 快递API - bash - 如何在 bash 脚本中多次使用带有“-”(破折号)的标准输入?
- java - 应用程序不会显示 mediaPlayer