Home > Mobile >  How to calculating interval days by factor in R
How to calculating interval days by factor in R

Time:05-11

I have this dataset and I would like to calculate the duration of days for each ID. How can I do this? If the date jumped from the 26th to the 30th for example, I would like those days to be counted as well. I tried with summarise() and aggregate() but no success.


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)

Expected output example

> output
id   days
A     7
B     9

CodePudding user response:

df %>% 
  group_by(id) %>% 
  summarise(days=difftime(max(date),min(date), units = "day"))

  • Related