Fast way to count days from a list between multiple date ranges in R?

Perhaps we can use

library(dplyr)
library(purrr)
library(tidyr)
library(zoo)
DF %>% 
  mutate(across(ends_with("Date"), as.Date),
         new = map2(StartDate, EndDate,
        ~ tibble(days = seq(.x, .y, by = 'day'), 
      Quarter = cut(days, breaks = seq(.x, .y, by = 'quarter'))))) %>% 
   unnest(c(new)) %>% 
   group_by(ItemName, StartDate, EndDate, Quarter = as.yearqtr(Quarter)) %>%
   summarise(n = n(), .groups = 'drop')

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top