【发布时间】:2019-10-16 22:14:54
【问题描述】:
我有两个具有两个地址列的数据集。我想通过公共地址合并两个数据集。但是有些地址是十字路口,街道名称的顺序在每个数据集中都不同。有没有办法让 Rstudio 逐字比较字符串,如果匹配的单词超过两个,请告诉我?一个例子是:
“拉格莱斯街上的卡博特街”和“卡博特街上的拉格莱斯街”
【问题讨论】:
标签: r string string-comparison
我有两个具有两个地址列的数据集。我想通过公共地址合并两个数据集。但是有些地址是十字路口,街道名称的顺序在每个数据集中都不同。有没有办法让 Rstudio 逐字比较字符串,如果匹配的单词超过两个,请告诉我?一个例子是:
“拉格莱斯街上的卡博特街”和“卡博特街上的拉格莱斯街”
【问题讨论】:
标签: r string string-comparison
此代码按字母顺序重新排列地址中的单词,因此您可以测试两个地址是否相同
library(stringr)
df = data.frame(address = c("CABOT ST AT RUGGLES ST", "RUGGLES ST AT CABOT ST"))
# split the address into words
list_split <- str_split(df$address,' ')
#[[1]]
#[1] "CABOT" "ST" "AT" "RUGGLES" "ST"
#[[2]]
#[1] "RUGGLES" "ST" "AT" "CABOT" "ST"
# sort the words
list_sort <- map(list_split, sort)
#[[1]]
#[1] "AT" "CABOT" "RUGGLES" "ST" "ST"
#[[2]]
#[1] "AT" "CABOT" "RUGGLES" "ST" "ST"
# paste all the words reordered together
list_pasted <- map(list_sort,function(x) paste(x,collapse= " "))
#[[1]]
#[1] "AT CABOT RUGGLES ST ST"
#[[2]]
# [1] "AT CABOT RUGGLES ST ST"
# unlist to convert to vector and assign to a new column
df$address_sorted <- unlist(list_pasted)
# address address_sorted
#1 CABOT ST AT RUGGLES ST AT CABOT RUGGLES ST ST
#2 RUGGLES ST AT CABOT ST AT CABOT RUGGLES ST ST
如果您有两个地址列,您可以对另一列执行相同操作并将它们一起比较
【讨论】:
我不确定简单地将两个字符串比较两个以上的相似词是否足以解决您的问题。但是,可以使用stringr 包中的str_split 函数来完成此操作。我还添加了一种从比较中删除不需要的词的方法,例如“ST”和“AT”:
# List of words to exclude from the comparisons
excluded <- c("ST", "AT")
# Addresses to compare
ad_1 <- "CABOT ST AT RUGGLES ST"
ad_2 <- "RUGGLES ST AT CABOT ST"
# Get unique list of words in each address
ad_1_d <- unique(str_split(ad_1, " ")[[1]])
ad_2_d <- unique(str_split(ad_2, " ")[[1]])
# Remove words from the vector above
ad_1_d <- ad_1_d[!ad_1_d %in% excluded]
ad_2_d <- ad_2_d[!ad_2_d %in% excluded]
if (sum(ad_1_d %in% ad_2_d) >= 2 || sum(ad_2_d %in% ad_1_d) >= 2) {
message("Similar addresses.")
}
【讨论】: