%overlaps% determines if two date ranges overlap at all and returns a logical value. Interval returns the number of days of the overlapping part of the two date periods. Inspired by the eponymous SQL-functions.

x %overlaps% y

Overlap(x, y)

Interval(x, y)

Arguments

x

range 1, vector of 2 numeric values or matrix with 2 columns, the first defining the left point the second the right point of the range.

y

range 2, vector of 2 numeric values or matrix with 2 columns, the first defining the left point the second the right point of the range.

Details

%overlaps% returns TRUE or FALSE depending on if the two ranges overlap. The function Overlap returns the range of the overlapping region as numeric value. This will be 0, if the ranges do not overlap.
Interval returns the width of the empty space between 2 ranges. Again this will be 0 if the ranges overlap.

To handle overlapping ranges there are 4 cases to consider:


range a:     |--------------|
range b:  |-----|
range c:              |--------|
range d:           |-----|
          1  2  3  4  5  6  7  8

Ranges a and b overlap, the function Overlap will return the absolute value of the overlapping region (which will be 3 - 2 = 1 in this case). The result will be the same for Overlap(a, b) and Overlap(b, a).
Interval will have a direction. Ranges b and c do not overlap, Overlap will return 0, %overlaps% FALSE. Interval will return 2 for the case Interval(a, b) and -2 for Interval(b, a).

This functions can be of value, if one has to decide, whether confidence intervals overlap or not.

Value

returns a logical vector (match or not for each element of x).
Interval and Overlap return a numeric vector.

Author

Andri Signorell <andri@signorell.net>

See also

similar operators: Between, %like%
for calculating the overlapping time: difftime

Examples

as.Date(c("2012-01-03", "2012-02-03")) %overlaps%
  as.Date(c("2012-03-01", "2012-03-03"))
#> [1] FALSE
as.Date(c("2012-01-03", "2012-02-03")) %overlaps%
  as.Date(c("2012-01-15", "2012-01-21"))
#> [1] TRUE

Interval(as.Date(c("2012-01-03", "2012-02-03")), as.Date(c("2012-03-01", "2012-03-03")))
#> [1] 27


# both ranges are recyled if necessary
as.Date("2012-01-03") %overlaps% as.Date(c("2012-03-01", "2012-03-03"))
#> [1] FALSE

# works with numerics as well
c(1, 18) %overlaps% c(10, 45)
#> [1] TRUE