Created
November 1, 2016 20:58
-
-
Save tgh0831/a21407f8d9f94333ed3064c107e47180 to your computer and use it in GitHub Desktop.
Fast Overlaps example using the data.table package's foverlaps() function. Uses lubridate to convert text values for date and time to POSIXct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require(data.table) | |
require(lubridate) | |
#create the data frames | |
#x is a data table with a list of events to match against the different dates in x to see if there is overlap | |
x = data.table( | |
eventid=c(1,2,3), | |
start =mdy_hms(c('10/1/2016 04:30:00','10/1/2016 18:02:00','10/2/2016 14:21:00')), | |
end =mdy_hms(c('10/1/2016 05:43:00','10/2/2016 01:23:00','10/4/2016 08:54:00')) | |
) | |
#y is a data table with a list of all dates | |
y = data.table( | |
date =c('10/1/2016','10/2/2016','10/3/2016','10/4/2016','10/5/2016','10/6/2016'), | |
start=mdy_hms(c('10/1/2016 00:00:00','10/2/2016 00:00:00','10/3/2016 00:00:00','10/4/2016 00:00:00','10/5/2016 00:00:00','10/6/2016 00:00:00')), | |
end =mdy_hms(c('10/1/2016 23:59:59','10/2/2016 23:59:59','10/3/2016 23:59:59','10/4/2016 23:59:59','10/5/2016 23:59:59','10/6/2016 23:59:59')) | |
) | |
#set the key on y to match with | |
setkey(y,start,end) | |
#use the foverlaps function to match | |
# | |
#note that eventid 1 matches one date only | |
# eventid 2 matches two dates | |
# eventid 3 matches three dates | |
# | |
result <- foverlaps(x,y,type="any") | |
#show results | |
x | |
y | |
result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment