【问题标题】:Combining Multiple Fuzzy Joins组合多个模糊连接
【发布时间】:2022-01-10 07:48:48
【问题描述】:

使用 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 为真,我正在尝试执行“内部连接”:

Condition_1

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

  • 如果 table_1$date BETWEEN(table_2$date_2,table_2$date_3)

Condition_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 &gt;= date_2, date_1 &lt;= date_3)。这似乎是一种低效的做事方式 - 或者这是完成此任务的唯一方法,因为默认情况下必须在所有行上运行模糊连接以查看是否满足“id”条件,然后只有“日期”条件是否满足?

【问题讨论】:

    标签: sql r dplyr data-manipulation


    【解决方案1】:

    如果我们想在循环中执行此操作,请遍历变量部分,即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
    

    【讨论】:

    • @akrun:非常感谢您的回答!我还是“purrr”库的新手——你能解释一下以下两行代码吗?
    • 1) map_dfr(c("id1", "id2"), ~
    • 2) 排列(across(everything()))
    • 还有其他方法可以让您准备好答案“final_2”吗?非常感谢!
    • @stats555 1) map 循环遍历by 的向量,_dfr 是在join/distinct, 2) the arrange 的输出上绑定所有列表输出确保我可以检查您的原始 final 对象,该对象具有不同的行顺序。可能还有其他方法
    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2017-01-08
    • 2017-01-31
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多