Expand Dates Between

A few weeks ago I helped someone who needed to expand a data frame that included events (with a start and stop date for each) to one that had rows for every date in an event (including start and stop) … the code below gives a reproducible example of how to do that with dplyr:

library(dplyr)

start_time <- sample(seq(as.Date("1999/1/1"), as.Date("1999/12/31"), "days"), 5)
end_time <- start_time + sample(2:4, size = length(start_time), replace = TRUE)
data_frame(start = start_time, end = end_time)
start end
1999-03-24 1999-03-27
1999-10-21 1999-10-23
1999-03-20 1999-03-24
1999-12-05 1999-12-07
1999-11-28 1999-12-02
data_frame(start = start_time, end = end_time) %>%
  mutate(id = 1:nrow(.)) %>%
  rowwise() %>%
  do(data.frame(id=.$id, days=seq(.$start,.$end,by="days")))
id days
1 1999-03-24
1 1999-03-25
1 1999-03-26
1 1999-03-27
2 1999-10-21
2 1999-10-22
2 1999-10-23
3 1999-03-20
3 1999-03-21
3 1999-03-22
3 1999-03-23
3 1999-03-24
4 1999-12-05
4 1999-12-06
4 1999-12-07
5 1999-11-28
5 1999-11-29
5 1999-11-30
5 1999-12-01
5 1999-12-02

This borrows from a SO post that also includes a data.table solution.

Related