Search code examples
rtimeintervalslubridate

Sum total unique time in lubridate intervals


I have multiple intervals and I'd like to figure out how much time they represent. The problem is that my intervals overlap. Here's a basic example. Imagine that I have one interval that starts an hour ago and runs until an hour from now, and I have another interval that starts now and runs for two hours. Each of the intervals is 2 hours long. Because they overlap, they describe a total of 3 hours.

library(lubridate)
interval1 <- interval(Sys.time() - hours(1), Sys.time() + hours(1))
interval2 <- interval(Sys.time(), Sys.time() + hours(2))

Is there a way to sum the total unique time represented by multiple intervals? My desired answer in this example is 3 hours.


Solution

  • You could union those both intervals and calculate the length:

    library(lubridate)
    
    interval1 <- interval(Sys.time() - hours(1), Sys.time() + hours(1))
    interval2 <- interval(Sys.time(), Sys.time() + hours(2))
    
    my_interval <- union(interval1, interval2)
    
    as.duration(my_interval)
    # "10800.9256539345s (~3 hours)"
    

    If the intervals don't necessarily overlap, you could do add the length of both intervals and substract the intersection of both:

    if (is.na(intersect(interval1, interval2))) {
      as.duration(interval1) + as.duration(interval2)
    } else {
      as.duration(interval1) + as.duration(interval2) - as.duration(intersect(interval1, interval2))
    }