You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中实现表格整词模糊匹配:仅匹配完整单词

问题描述

现有可复现代码如下:

library(tidyverse)
a <- tibble(navn=c("Oslo kommune", "Oslo kommune", "Kommunen i Os", "Kommunen i Eidsberg", "Eid fylkeskommune"), person=c("a", "c", "b", "a", "b"))
b <- tibble(knavn=c("Oslo", "Eid", "Eidsberg", "Os"), tall=c(1,2,3,4))

library(fuzzyjoin)
library(stringr)

c <- a %>%
  fuzzy_left_join(b, by=c("navn"="knavn"), match_fun=str_detect)

当前代码存在错误匹配:"Oslo kommune"会同时匹配"Oslo"和"Os","Kommunen i Eidsberg"会同时匹配"Eidsberg"和"Eid"。需要实现仅匹配navn字段中的完整单词与knavn字段的单词完全一致,最终期望结果如下:

tibble(navn=c("Oslo kommune", "Oslo kommune", "Kommunen i Os", "Kommunen i Eidsberg", "Eid fylkeskommune"), person=c("a", "c", "b", "a", "b"), knavn=c("Oslo","Oslo", "Os", "Eidsberg", "Eid"),tall=c(1,1,4,3,2))
解决方案

核心是利用单词边界正则实现精准的完整单词匹配,修改fuzzy_left_join的match_fun逻辑即可:

library(tidyverse)
library(fuzzyjoin)
library(stringr)

a <- tibble(navn=c("Oslo kommune", "Oslo kommune", "Kommunen i Os", "Kommunen i Eidsberg", "Eid fylkeskommune"), person=c("a", "c", "b", "a", "b"))
b <- tibble(knavn=c("Oslo", "Eid", "Eidsberg", "Os"), tall=c(1,2,3,4))

c <- a %>%
  fuzzy_left_join(
    b,
    by = c("navn" = "knavn"),
    match_fun = function(x, y) {
      str_detect(x, regex(y, boundary = "word"))
    }
  )

关键说明

  • regex(y, boundary = "word")会为每个knavn字符串添加单词边界约束(等价于正则表达式中的\b),确保仅匹配navn中独立的完整单词,而非子串。
  • 此逻辑可避免短单词被误匹配到包含它的长单词中,完美满足需求:"Oslo kommune"仅匹配"Oslo","Kommunen i Eidsberg"仅匹配"Eidsberg",其余条目也能精准对应。

内容的提问来源于stack exchange,提问作者Ajern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:20:30