简体   繁体   中英

Difftime() Between Time Intervals? (R)

I want to know if it is possible to calculate the difference in time between two time intervals in R.

With single dates, I know i can use the difftime() function.

And I know that i can use the int_overlaps() function from the lubridate package to know if two intervals overlap each other (it provides a TRUE/FALSE output).

Now, instead of a TRUE/FALSE output, is there a function that could give me the time difference between the two intervals? If they overlap each other, the output would be 0. And if not, the output would be the time difference between the most proximal borders of each interval.

Ex.:


int1 = 2020-03-10 11:00:00--2020-03-10 14:00:00

int2 = 2020-03-10 12:00:00--2020-03-10 13:00:00

int3 = 2020-03-10 08:00:00--2020-03-10 11:30:00

Function output:

int1 and int2 -> 0

int1 and int3 -> 0

int2 and int3 -> 0.5 hours

You can write your own short function with the desired outputs.

Firstly, get the function to test for an overlap using int_overlaps , and if TRUE , return 0 seconds using make_difftime(0) .

If there is no overlap, you can make use of int_start and int_end from the lubridate package to get the start and end of your two intervals, which you then compare with difftime .

For completeness, it is sensible to add some error checking to ensure both the inputs are single interval objects:

library(lubridate)

interval_difftime <- function(a, b)
{
  stopifnot(is.interval(a) & is.interval(b) & length(a) == 1 & length(b) == 1)

  if (int_overlaps(a, b)) return(make_difftime(0))
  if (int_end(a) < int_start(b)) return(-difftime(int_start(b), int_end(a)))
  else return(difftime(int_start(a), int_end(b)))
}

The ordering will work in the same way as difftime , in that if you put the later interval first, you will get a positive difference, but if you put the earlier one first, it will give a negative difference.

Suppose I have the following intervals x , y and z :

n <- now()
x <- interval(n, n + 5)
y <- interval(n + 3, n + 8)
z <- interval(n + 6, n + 10)

Then the following tests give the desired results: a time difference of zero if the intervals overlap; otherwise the difference between the proximal ends of the intervals according to the order:

interval_difftime(x, y)
#> Time difference of 0 secs
interval_difftime(x, z)
#> Time difference of -1 secs
interval_difftime(z, x)
#> Time difference of 1 secs

Created on 2020-03-16 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM