[英]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
現在,我知道如何分兩部分做到這一點:
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.