我有這個資料集,我想計算每個 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
uj5u.com熱心網友回復:
df %>%
group_by(id) %>%
summarise(days=difftime(max(date),min(date), units = "day"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472596.html