根据地址字符串的部分匹配合并数据帧

时间:2015-07-25 20:38:59

标签: r merge string-matching fuzzy-comparison

我正在寻找一种匹配两个不同地址数据帧的方法。两者都包含一串文本(在我的示例中为“Line”列),邮政编码/邮政编码类型标识符(“PC”列)和唯一的Ref或ID代码。我需要将匹配的数据放在一个新的数据框中,格式如下:DF1 $ Line,DF1 $ PD,DF2 $ Line,DF2 $ PD,Ref,ID和某种数字详细说明匹配的强度(这是基于下面的示例代码)。

我的实际数据集包含数千条记录,我一直在使用“PC”列来对两个数据集进行子集,然后沿着this的行执行某种匹配,但结果匹配我觉得完全错了。

这是一个与我的数据类似的虚构数据集(在这些示例中,每个数据集中的行彼此对应,不幸的是,我的实际数据没有像这样格式化)。

DF1 <- data.frame(
Line = c("64 London Street, Jasper","46 London Road, Flat 2, Jasper","99 York Parade, Yorkie","99 Parade Road, Placename","29 Road Street, Townplace","92 Parade Street, Yorky"),
PC = c("ZZ1 4TY","ZZ1 4TY","PP1 9TR","ZZ1 4TY","PP1 9TR","PP1 9RT"),
Ref = c("123451","567348","23412","98734","43223","32453")
)

DF2 <- data.frame(    
Line = c("64 London St, Jasper","Flat 2, 46 Road, London, Jasper","99 York Parade, Yorky","99 Parade Road, Placenames","Flat 3, 29 Road Street, Townplace, Townplace","92 Street, Parade, Yorkie"),
PC = c("ZZ1 4TY","ZZ1 4TY","PP1 9TR","ZZ1 4TY","PP1 9TR","PP1 9RT"),
ID = c("ABGED","GGFRW","UYTER","RTERF","WERWE","OYUIY")
)

任何有助于解决此问题的帮助都会非常感激,任何帮助我量化匹配精确度的指标都会非常受欢迎。谢谢。

2 个答案:

答案 0 :(得分:1)

这是我的基础R解决方案让我知道,如果我得到它。

 DF3 <- merge(DF1, DF2, by = "PC")
 DF3[!duplicated(DF3$Ref) , ]
        PC                         Line.x    Ref                    Line.y    ID
1  PP1 9RT        92 Parade Street, Yorky  32453 92 Street, Parade, Yorkie OYUIY
2  PP1 9TR         99 York Parade, Yorkie  23412     99 York Parade, Yorky UYTER
4  PP1 9TR      29 Road Street, Townplace  43223     99 York Parade, Yorky UYTER
6  ZZ1 4TY       64 London Street, Jasper 123451      64 London St, Jasper ABGED
9  ZZ1 4TY 46 London Road, Flat 2, Jasper 567348      64 London St, Jasper ABGED
12 ZZ1 4TY      99 Parade Road, Placename  98734      64 London St, Jasper ABGED

答案 1 :(得分:0)

我会考虑首先使用agrep评估潜在匹配:

for (i in 1:length(DF1$Line)) {
  matchDF1 <- agrep(pattern = DF1$Line[i], x = DF2$Line, max.distance = 0.5,
                    value = TRUE) 
}