R语言中是否存在支持自定义匹配规则的表连接函数或R包?
自定义匹配规则的tibble全连接实现方案
下面提供两种原生实现方案,无需引入fuzzyjoin等额外包,均支持自定义匹配规则。
方案1:基于dplyr/tidyr实现(可读性优先)
适合小数据集,逻辑直观易修改:
library(tidyverse) # 1. 生成所有匹配成功的交叉行 matched_rows <- x %>% rowwise() %>% reframe( id.x = id, my_col = my_col, y[str_detect(my_col, fixed(other_col)), ] ) %>% rename(id.y = id) # 2. 提取x表未匹配的行 unmatched_x <- x %>% anti_join(matched_rows, by = c("id" = "id.x")) %>% transmute(id.x = id, my_col = my_col, id.y = NA_integer_, other_col = NA_character_) # 3. 提取y表未匹配的行 unmatched_y <- y %>% anti_join(matched_rows, by = c("id" = "id.y", "other_col" = "other_col")) %>% transmute(id.x = NA_integer_, my_col = NA_character_, id.y = id, other_col = other_col) # 4. 合并得到全连接结果 final_result <- bind_rows(matched_rows, unmatched_x, unmatched_y) %>% arrange(id.x, id.y)
方案2:基于data.table实现(性能优先)
适合万行以上的大数据集,利用非等值连接特性避免逐行遍历,效率提升非常明显:
library(data.table) library(stringr) # 转换为data.table格式 setDT(x) setDT(y) # 1. 生成所有匹配成功的交叉行 matched_dt <- x[y, on = .(str_detect(my_col, fixed(other_col))), allow.cartesian = TRUE, .(id.x = x.id, my_col, id.y = i.id, other_col) ] # 2. 合并未匹配的x、y行得到全连接结果 final_dt <- rbind( matched_dt, x[!id %in% matched_dt$id.x, .(id.x = id, my_col, id.y = NA_integer_, other_col = NA_character_)], y[!id %in% matched_dt$id.y, .(id.x = NA_integer_, my_col = NA_character_, id.y = id, other_col = other_col)] )[order(id.x, id.y)]
匹配规则自定义方式
两种方案均可灵活替换匹配逻辑,只需把代码中的str_detect(my_col, fixed(other_col))条件替换为你自定义的匹配函数返回值即可,只要返回布尔值就能正常执行匹配。
内容的提问来源于stack exchange,提问作者CubicInfinity
相关产品推荐
相关产品推荐

