繁体   English   中英

R:组合多个模糊连接

[英]R: Combining Multiple Fuzzy Joins

使用 R 编程语言,我有以下两个表(在我的实际问题中,所有日期都以“因子”类型提供给我):

table_1 = data.frame(id1 = c("123 A", "123BB", "12 5", "12--5"), id2 = c("11", "12", "14", "13"),
date_1 = c("2010-01-31","2010-01-31", "2015-01-31", "2018-01-31" ))

table_1$id1 = as.factor(table_1$id1)
table_1$id2 = as.factor(table_1$id2)
table_1$date_1 = as.factor(table_1$date_1)

table_2 = data.frame(id1 = c("0123", "1233", "125  .", "125_"), id2 = c("111", "112", "14", "113"),
date_2 = c("2009-01-31","2010-01-31", "2010-01-31", "2010-01-31" ),
date_3 = c("2011-01-31","2010-01-31", "2020-01-31", "2020-01-31" ))


table_2$id1 = as.factor(table_2$id1)
table_2$id2 = as.factor(table_2$id2)
table_2$date_2 = as.factor(table_2$date_2)
table_2$date_3 = as.factor(table_2$date_3)

如果条件 1 或条件 2 为真,我将尝试执行“内部连接”:

条件_1

  • 如果 table_1$id “模糊相等” table_2$id AND

  • if table_1$date BETWEEN(table_2$date_2,table_2$date_3)

条件_2

  • 如果 table_1$id2 “模糊相等” table_2$id2

现在,我知道如何分两部分做到这一点:

library(dplyr)
library(fuzzyjoin)

part_1 =  stringdist_inner_join(table_1, table_2, by = "id1", max_dist = 2) %>%
  filter(date_1 >= date_2, date_1 <= date_3) 

part_2 =  stringdist_inner_join(table_1, table_2, by = "id2", max_dist = 2) 

combine = rbind(part_1, part_2)

final = combine[!duplicated(combine[c(1,2,3,4,5,6,7)]),]

我的问题

  • 有没有一种“更好”的方式来运行这个连接,而不是两个单独的部分?

  • 似乎“part_1”中的 SQL 查询首先对所有记录执行模糊联接,然后只保留满足日期条件的相关记录,即filter(date_1 >= date_2, date_1 <= date_3) 这似乎是一种低效的做事方式 - 或者这是完成此任务的唯一方法,因为默认情况下必须在所有行上运行模糊连接以查看是否满足“id”条件,然后只有“日期”条件是否满足?

谢谢!

如果我们想在循环中执行此操作,请遍历变量部分,即by

library(purrr)
library(fuzzyjoin)
library(dplyr)
final2 <- map_dfr(c("id1", "id2"),  ~
       stringdist_inner_join(table_1, table_2, by = .x, max_dist = 2)) %>%
       distinct %>%
       arrange(across(everything()))

-检查

> all.equal(final %>% 
         arrange(across(everything())), final2)
[1] TRUE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM