Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use intersect() function with date ranges in R

Tags:

r

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 of c,f and h are:

> 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
> 

But, when I give a different date/time range. The intersect function does not work. For example: If I change the time of the variable d and e from 09:00:00-12:00:00 to 09:00:00 - 10:00:00, I am expecting the intersect function to give me the minutes for 1 hour that is common.

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 get numeric(0). Can someone please help me with this.

like image 959
Jennifer Logan Avatar asked Feb 13 '26 03:02

Jennifer Logan


1 Answers

For the sake of avoiding answering in the comments:

As J_F mentions above, you need to use the intersect function from lubridate. In case you face problems because you need intersect from both lubridate and dplyr you can use the double colon ::.

Double colon :: is used to specify from which package you call a function and overcomes masking. So in your 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 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
like image 141
Col Bates - collynomial Avatar answered Feb 22 '26 23:02

Col Bates - collynomial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!