如何通过R中的因素计算间隔天数
How to calculating interval days by factor in R
我有这个数据集,我想计算每个 ID 的天数。我怎样才能做到这一点?例如,如果日期从 26 日跳到 30 日,我希望这些天也被计算在内。我试过 summarise()
和 aggregate()
但没有成功。
library(lubridate)
library(dplyr)
id <- as.factor(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
date <- ymd_hms(c("2017-11-26 09:00:00", "2017-11-26 09:05:00", "2017-11-30 09:00:00",
"2017-11-30 09:05:00", "2017-12-02 09:00:00", "2017-11-26 09:00:00",
"2017-11-26 09:05:00", "2017-11-30 09:00:00", "2017-11-30 09:05:00", "2017-12-04 09:00:00"))
df <- tibble(id,date)
预期输出示例
> output
id days
A 7
B 9
df %>%
group_by(id) %>%
summarise(days=difftime(max(date),min(date), units = "day"))
我有这个数据集,我想计算每个 ID 的天数。我怎样才能做到这一点?例如,如果日期从 26 日跳到 30 日,我希望这些天也被计算在内。我试过 summarise()
和 aggregate()
但没有成功。
library(lubridate)
library(dplyr)
id <- as.factor(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
date <- ymd_hms(c("2017-11-26 09:00:00", "2017-11-26 09:05:00", "2017-11-30 09:00:00",
"2017-11-30 09:05:00", "2017-12-02 09:00:00", "2017-11-26 09:00:00",
"2017-11-26 09:05:00", "2017-11-30 09:00:00", "2017-11-30 09:05:00", "2017-12-04 09:00:00"))
df <- tibble(id,date)
预期输出示例
> output
id days
A 7
B 9
df %>%
group_by(id) %>%
summarise(days=difftime(max(date),min(date), units = "day"))