Combine two dataframes meeting conditional criteria in R

Solution 1:

dfa <- data.frame(
  date = c("2021-01-01", "2021-02-02", "2021-02-05"),
  patient = c("one", "two", "three"))

dfb <- data.frame(
  start = c("2020-12-31", "2021-02-01"),
  end = c("2021-01-02", "2021-02-03"),
  patient = c("one", "one"))

dfa$date <- as.Date(dfa$date, "%Y-%m-%d")
dfb$start <- as.Date(dfb$start, "%Y-%m-%d")
dfb$end <- as.Date(dfb$end, "%Y-%m-%d")

dfa
#>         date patient
#> 1 2021-01-01     one
#> 2 2021-02-02     two
#> 3 2021-02-05   three
dfb
#>        start        end patient
#> 1 2020-12-31 2021-01-02     one
#> 2 2021-02-01 2021-02-03     one

library(tidyverse)
library(fuzzyjoin)

fuzzy_anti_join(
  x = dfa, 
  y = dfb, 
  by = c("patient", "date" = "start", "date" = "end"),
  match_fun = list(`==`, `>=`, `<=`)
  ) %>% 
  transmute(patient, start = date, end = date) %>% 
  bind_rows(dfb)
#>   patient      start        end
#> 1     two 2021-02-02 2021-02-02
#> 2   three 2021-02-05 2021-02-05
#> 3     one 2020-12-31 2021-01-02
#> 4     one 2021-02-01 2021-02-03

Created on 2022-01-22 by the reprex package (v2.0.1)

data.table

library(magrittr)
library(data.table)

setDT(dfa)
setDT(dfb)

tmp <- dfa[!dfb, on = list(patient, date >= start, date <= end)] %>% 
  .[, `:=`(start = date, end = date, date = NULL)]

l <- list(tmp, dfb)

rbindlist(l = l, use.names = TRUE)
#>    patient      start        end
#> 1:     two 2021-02-02 2021-02-02
#> 2:   three 2021-02-05 2021-02-05
#> 3:     one 2020-12-31 2021-01-02
#> 4:     one 2021-02-01 2021-02-03

Created on 2022-01-22 by the reprex package (v2.0.1)