Other option using fuzzyjoin
library(dplyr)
library(lubridate)
library(fuzzyjoin)
DT1 <- data.frame(
stringsAsFactors = FALSE,
ID = c("A", "B"),
Date = c("01/04/2020", "05/04/2020")
)
DT2 <- data.frame(
stringsAsFactors = FALSE,
ID = c("A", "A", "A", "A", "B", "B", "B", "C"),
Date = c("01/03/2020","30/03/2020",
"01/04/2020","15/04/2020","30/03/2020","01/04/2020",
"15/04/2020","15/04/2020")
)
DT1 %>%
mutate(Date = dmy(Date)) %>%
fuzzy_left_join(DT2 %>%
mutate(Date = dmy(Date)),
by = c("ID" = "ID",
"Date" = "Date"),
match_fun = list(`==`, `<=`)) %>%
select(ID = ID.y, Date = Date.y)
#> ID Date
#> 1 A 2020-04-01
#> 2 A 2020-04-15
#> 3 B 2020-04-15