Problem: I have a data set that contains interval data with start and end dates and my goal is it to add rows to that data set that reflect the potential gaps between these intervals (per group). The complexity is that the already existing intervals may overlap and there might be an arbitrary number of gaps.
Example: We have start and end dates showing from when to when a person has occupied an apartment. There may have been multiple people at one apartment at the same time and there needs to be rows added for the time the apartment has been "empty".
Example data:
example_dates <- structure(list(apartment = c("A", "A", "A", "A", "B", "B",
"B", "C", "C", "C"),
start_date = structure(c(1640995200, 1642291200,
1649980800, 1655769600, 1644451200, 1646092800, 1659312000, 1646438400,
1649376000, 1664582400),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
end_date = structure(c(1642204800, 1648166400, 1655683200,
1668643200, 1655251200, 1653868800, 1667260800, 1654819200,
1661385600, 1668470400), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
status = c("person in apartment", "person in apartment",
"person in apartment", "person in apartment", "person in apartment",
"person in apartment", "person in apartment", "person in apartment",
"person in apartment", "person in apartment")),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))
Desired output:
desired_outcome <- structure(list(apartment = c("A", "A", "A", "A", "A", "B",
"B", "B", "B", "C", "C", "C", "C"),
start_date = structure(c(1640995200, 1642291200, 1648252800,
1649980800, 1655769600, 1644451200, 1646092800,
1655337600, 1659312000, 1646438400, 1649376000, 1661472000, 1664582400),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
end_date = structure(c(1642204800, 1648166400, 1649894400, 1655683200, 1668643200, 1655251200, 1653868800,
1659225600, 1667260800, 1654819200, 1661385600, 1664496000, 1668470400),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
status = c("person in apartment", "person in apartment", "apartment empty",
"person in apartment", "person in apartment", "person in apartment",
"person in apartment", "apartment empty", "person in apartment", "person in apartment",
"person in apartment", "apartment empty", "person in apartment"
)),
class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -13L))