Utilizing the intersect() function to work with date ranges in R

In your code, you have two vectors that you want to plot as lines. Additionally, you are looking to find the intersection points of these lines, even if there are multiple points of intersection. It is important to note that this occurs when the values on the x-axis are not consecutive integers and do not have a difference of 1 for consecutive points.

Question:

Here is my code:

a<-"2015-12-13 09:00:00"           
b<-"2015-12-13 12:00:00"
c<-interval(a,b)
d<-"2015-12-13 09:00:00"           
e<-"2015-12-13 12:00:00"
f<-interval(d,e)
h<-intersect(c,f)
h

The values assigned to the variables

c

,

f

, and

h

are as follows:
“””.

> h
[1] 10800
> c
[1] 2015-12-13 09:00:00 UTC--2015-12-13 12:00:00 UTC
> f
[1] 2015-12-13 09:00:00 UTC--2015-12-13 12:00:00 UTC
> 

However, when I modify the date/time range, the
intersect function
stops functioning. For instance, if I alter the time of variables d and e from

09:00:00-12:00:00

to

09:00:00 - 10:00:00

, my expectation is that the

intersect

function will provide me with the minutes that are shared within a one-hour period.

a<-"2015-12-13 09:00:00"           
b<-"2015-12-13 12:00:00"
c<-interval(a,b)
d<-"2015-12-13 09:00:00"           
e<-"2015-12-13 10:00:00"
f<-interval(d,e)
h<-intersect(c,f)
h

Output:

numeric(0)
> c
[1] 2015-12-13 09:00:00 UTC--2015-12-13 12:00:00 UTC
> f
[1] 2015-12-13 09:00:00 UTC--2015-12-13 10:00:00 UTC

I’m receiving a numeric(0) result. Could someone assist me with this issue, please?


Solution:

To prevent the need for responding in the comments:

According to J_F’s comment, the

intersect

function should be utilized from

lubridate

. If you encounter difficulties due to requiring

intersect

from both

lubridate

and

dplyr

, you can employ the double colon

::

.

The double colon, represented as

::

, is utilized to indicate the package from which you are calling a function and resolves the issue of masking. Thus, in your code, you would utilize it as follows:

a<-"2015-12-13 09:00:00"           
b<-"2015-12-13 12:00:00"
c<-interval(a,b)
d<-"2015-12-13 09:00:00"           
e<-"2015-12-13 10:00:00"
f<-interval(d,e)
h<-lubridate::intersect(c,f)
h
[1] 2015-12-13 09:00:00 UTC--2015-12-13 10:00:00 UTC

Frequently Asked Questions

Posted in Uncategorized