Search code examples
rtimemergestrftime

Merge two datasets based on multiple columns but make time column flexible within minute range


I have a dataset that looks like this

id|date     |social_id     | race    | age | time        |Location
 1  04/02/19  2000001          W        29    "04:10:05"  HA
 2  04/06/20  2000002          B        22    "05:12:49"  CA
 3  04/12/20  2000021          B        26    "09:13:32"  MA
 4  08/14/20  2000026          A        29    "06:12:34"  VT

and the second dataset looks like this

    id2|date     |social_id     | race    | age | time| sex
      1  04/02/19  2000001          W        29    "04:30:05"  M
      2  04/06/20  2000002          B        22    "05:49:49"  F
      3  04/12/20  2000021          B        26    "10:13:32"  M
      4  08/14/20  2000026          A        29    "06:19:54"  F

Note that all columns are the same except for time. I would like to do a join based on these columns

date, social_id, race_age, and time. However time does not match for both datasets

df3 <- df1 %>% left_join(df2,by=c("date","social_id","race","time"))

is there a way to do a multiple column join but make an exception for time within a 45 minutes? Time is in string format so I adjusted for it by writing

abs(difftime(as.POSIXct(strptime(df1$time,format="%H:%M:%S")), as.POSIXct(strptime(df2$time,format="%H:%M:%S")),units = "mins")) <= 45

This works on its own and recognizes if the time string is within 45 minutes or not. How can I bring this together when i do the merge?

structure(list(id = 1:4, date = c("4/2/2019", "4/6/2020", "4/12/2020", 
"8/14/2020"), race = c("w", "b", "b", "a"), age = c(29L, 22L, 
26L, 29L), time = structure(c(15005L, 18769L, 33212L, 22354L), class = 
"ITime")), row.names = c(NA, 
-4L), class = "data.frame")

structure(list(id2 = 1:4, date = c("4/2/2019", "4/6/2020", "4/12/2020", 
"8/14/2020"), race = c("w", "b", "b", "a"), age = c(29L, 22L, 
26L, 29L), time = structure(c(16205L, 20989L, 36812L, 22794L), class = 
"ITime")), row.names = c(NA, 
-4L), class = "data.frame")

Solution

  • We could use round_date from lubridate

    library(dplyr)
    library(lubridate)
    library(stringr)
    df1 %>% 
        mutate(datetime = round_date(mdy_hms(str_c(date, time,
           sep = ' ')), '45 mins')) %>% 
        left_join(df2 %>%
           mutate(datetime = round_date(mdy_hms(str_c(date, time,
              sep = ' ')), '45 mins')), 
        by = c('datetime', 'id' = 'id2', 'race', 'age'))