【问题标题】:Imperfect String Matching不完美的字符串匹配
【发布时间】:2012-02-08 15:39:16
【问题描述】:

假设我有两列名称。第一列中的所有名称都在第二列中,但顺序是随机的,其中一些不是完美匹配。所以也许在一列中有 John Smith 的名字,而在第二列中有 John_smith 或 JonSmith。是否有任何相当简单的 R 方式来执行“最佳匹配”?

【问题讨论】:

标签: r


【解决方案1】:

给定一些这样的数据:

df<-data.frame(x=c('john doe','john smith','sally struthers'),y=c('John Smith','John_smith','JonSmith'))

通过几个gsubs 和tolower,你可以走得很远:

df$y.fix <- gsub('[[:punct:]]', ' ', df$y)
df$y.fix <- gsub(' ', '', df$y.fix)
df$y.fix <- tolower(df$y.fix)
df$x.fix <- tolower(gsub(' ', '', df$x))

那么agrep 就是你想要的:

> agrep(df$x.fix[2], df$y.fix)
[1] 1 2 3

对于更复杂的混淆字符串,请参阅this post from last week

【讨论】:

  • +1 表示tolower()gsub(),否则会在 levenshtein 距离中被高估。
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多