r中的模糊字符串匹配

Fuzzy string matching in r

我有 2 个数据集,每个数据集都超过 100K 行。我想根据模糊字符串匹配一列 ('movie title') 以及使用发布日期来合并它们。我在下面提供了两个数据集的样本。

数据集-1

itemid userid rating       time                              title release_date
99991    1673    835      3 1998-03-27                             mirage         1995
99992    1674    840      4 1998-03-29                         mamma roma         1962
99993    1675    851      3 1998-01-08                     sunchaser, the         1996
99994    1676    851      2 1997-10-01                   war at home, the         1996
99995    1677    854      3 1997-12-22                      sweet nothing         1995
99996    1678    863      1 1998-03-07                         mat' i syn         1997
99997    1679    863      3 1998-03-07                          b. monkey         1998
99998    1680    863      2 1998-03-07                      sliding doors         1998
99999    1681    896      3 1998-02-11                       you so crazy         1994
100000   1682    916      3 1997-11-29 scream of stone (schrei aus stein)         1991

数据集 - 2

itemid userid rating       time                                   title release_date
1    2844   4477      3 2013-03-09 fantã´mas - 〠l'ombre de la guillotine         1913
2    4936   8871      4 2013-05-05                                the bank         1915
3    4936  11628      3 2013-07-06                                the bank         1915
4    4972  16885      4 2013-08-19                   the birth of a nation         1915
5    5078  11628      2 2013-08-23                               the cheat         1915
6    6684   4222      3 2013-08-24                             the fireman         1916
7    6689   4222      3 2013-08-24                         the floorwalker         1916
8    7264   2092      4 2013-03-17                                the rink         1916
9    7264   5943      3 2013-05-12                                the rink         1916
10   7880  11628      4 2013-07-19                             easy street         1917

我看过 'agrep' 但它一次只能匹配一个字符串。 'stringdist' 函数很好,但您需要在循环中 运行 它,找到最小距离,然后继续进一步处理,考虑到数据集的大小,这非常耗时。由于需要模糊匹配,字符串可能有拼写错误和特殊字符。我环顾四周,找到了 'Lenenshtein' 和 'Jaro-Winkler' 方法。当你在字符串中有错别字时,我后来阅读的内容很有用。

在这种情况下,仅模糊匹配可能无法提供良好的结果,例如,一个数据集中的电影标题 'toy story' 可以与另一个数据集中的 'toy story 2' 匹配,这是不正确的。所以我需要考虑发布日期以确保匹配的电影是唯一的。

我想知道有没有不用循环的方法来完成这个任务?更糟糕的情况是,如果我必须使用循环,我怎样才能让它尽可能高效地工作。

我尝试了以下代码,但处理起来花费了太多时间。

for(i in 1:nrow(test))
  for(j in 1:nrow(test1))
  {

    test$title.match <- ifelse(jarowinkler(test$x[i], test1$x[j]) > 0.85,
                      test$title, NA)
  }

test - 包含 1682 个转换为小写的唯一电影名称 test1 - 包含 11451 个转换为小写的唯一电影名称

有没有办法避免 for 循环并使其工作得更快?

这种推动你前进的方法怎么样?您可以在看到结果后从 0.85 开始调整匹配度。然后,您可以使用 dplyr 按匹配的标题进行分组,并通过减去发布日期进行总结。任何零都表示相同的发布日期。

dataset-1$title.match <- ifelse(jarowinkler(dataset-1$title, dataset_2$title) > 0.85, dataset-1$title, NA)