0

I do a fuzzy_full_join of two tables in R requiring multiple keys to match. Some rows do not match. The output has duplicated the keys. This does not happen with a non-fuzzy full join. What is the best way to remove the duplicates? I have a solution, but it seems cumbersome.

Example:


x<-data.frame("id"=c(1,1,2,2), "time" = c(1,2,1,2), "meas1" = c(1,2,3,4))
y<-data.frame("id"=c(1,1,2,2), "time" =c(1,3,2,4),"meas2"=c(-1,-2,-3,-4))

# compare full_join output with fuzzy_full_join
full_join(x,y,by=c('id'='id','time'='time')) 
fuzzy_full_join(x,y,by=c('id'='id','time'='time'),match_fun=list(`==`,`==`))

# make fuzzy_full_join output match full_join output
fuzzy_full_join(x,y,by=c('id'='id','time'='time'),match_fun=list(`==`,`==`)) %>%
  mutate(id=if_else(is.na(id.x),id.y,id.x)) %>%
  select(-id.x,-id.y) %>%
  mutate(time=if_else(is.na(time.x),time.y,time.x)) %>%
  select(-time.y,-time.x)

1 Answer 1

1

We can use coalesce which might help reduce the code.

library(dplyr)
library(fuzzyjoin)

fuzzy_full_join(x,y,by=c('id'='id','time'='time'),match_fun=list(`==`,`==`)) %>%
  mutate(id=coalesce(id.x, id.y), time = coalesce(time.x, time.y)) %>%
  select(-matches('\\.x$|\\.y$'))

#  meas1 meas2 id time
#1     1    -1  1    1
#2     4    -3  2    2
#3     2    NA  1    2
#4     3    NA  2    1
#5    NA    -2  1    3
#6    NA    -4  2    4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.