我有两个数据集,它们有两个地址列。我想通过公共地址合并这两个数据集。但是一些地址是交叉口,每个数据集中街道名称的顺序是不同的。有没有办法让Rstudio逐字比较字符串,如果有两个以上的单词匹配,请告诉我?下面是一个例子:
“卡博街AT拉格斯街”和“卡博街拉格斯街”
发布于 2019-10-17 06:31:24
这段代码将地址中的单词按字母顺序重新排序,这样您就可以测试两个地址是否相同
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如果您有两个地址列,则可以对另一列执行相同的操作,并将它们进行比较
发布于 2019-10-17 06:22:29
我不确定简单地比较两个字符串中的两个以上相似的单词是否足以解决您的问题。但是,可以使用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.")
}https://stackoverflow.com/questions/58422350
复制相似问题