Search code examples
rintervalslubridate

Assign vector of time intervals to non-overlapping groups


I have vectors of Intervals created by the R package lubridate:

library(lubridate)
ints <- new("Interval", .Data = c(61379.0158998966, 61379.0158998966, 
                                  174450.142500162, 2105574.12809992, 
                                  1986079.47369981), 
            start = structure(c(1477895188.5302, 1477895188.5302, 
                                1478301991.7993, 1478488100.319, 
                                1478607594.9734), 
                              tzone = "America/New_York", class = c("POSIXct", "POSIXt")), 
            tzone = "America/New_York")
ints
#> [1] 2016-10-31 02:26:28 EDT--2016-10-31 19:29:27 EDT
#> [2] 2016-10-31 02:26:28 EDT--2016-10-31 19:29:27 EDT
#> [3] 2016-11-04 19:26:31 EDT--2016-11-06 18:54:01 EST
#> [4] 2016-11-06 22:08:20 EST--2016-12-01 07:01:14 EST
#> [5] 2016-11-08 07:19:54 EST--2016-12-01 07:01:14 EST

I'd like to pass this vector of Intevals to a function and have it return an identical-length vector of group membership, where group membership is determined by overlapping time intervals. In this example, the returned vector would be:

c(1, 1, 2, 3, 3)

lubridate is able to evaluate overlap of pairs of intervals with int_overlaps, but I'm hoping someone has already generalized this to identify groups of non-overlapping intervals.


Solution

  • We can use the int_overlaps from lubridate. The idea is to check whether there is any overlaps between the intervals on the current and the previous (lag) to return a logical vector, which we convert to integer with cumsum

    library(lubridate)
    library(dplyr)
    cumsum(!int_overlaps(ints, lag(ints, default = first(ints)))) + 1
    #[1] 1 1 2 3 3