rintervalslubridate

setdiff in lubridate


Trying to figure out why this doesn't work. What I'm looking to do is break up test_int_1 into 3 segements -> before test_init_2, test_init_2, after test_init_2.

library(lubridate)

test_int_1 <- interval(ymd_hms('2024-04-29 17:01:00'), ymd_hms('2024-04-29 18:00:00'))
test_int_2 <- interval(ymd_hms('2024-04-29 17:28:00'), ymd_hms('2024-04-29 17:56:00'))
test_int_2 %within% test_int_1

setdiff(test_int_1, test_int_2)
# Error in setdiff.Interval(test_int_1, test_int_2) : 
#  Cases 1 result in discontinuous intervals.

Not sure if I'm understanding setdiff correctly.


Solution

  • One way to do this using lubridate functions is as follows...

    int_diff(sort(c(int_start(c(test_int_1, test_int_2)),
                    int_end(c(test_int_1, test_int_2)))))
    
    [1] 2024-04-29 17:01:00 UTC--2024-04-29 17:28:00 UTC
    [2] 2024-04-29 17:28:00 UTC--2024-04-29 17:56:00 UTC
    [3] 2024-04-29 17:56:00 UTC--2024-04-29 18:00:00 UTC
    

    This simply creates a sorted vector of the end points of the intervals, and uses these to create the three intervals you are looking for.