逐字逐行比较字符串

Comparing strings word by word and row by row

我有两个具有两个地址列的数据集。我想通过公共地址合并这两个数据集。但是有些地址是交叉路口,街道名称的顺序在每个数据集中都是不同的。有没有办法让 Rstudio 逐字比较字符串,如果有两个以上的单词匹配,请告诉我?一个例子是:

"CABOT ST AT RUGGLES ST" 和 "RUGGLES ST AT CABOT 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.")
}

此代码将地址中的单词按字母顺序重新排序,这样您就可以测试两个地址是否相同

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

如果您有两个地址列,您可以对另一列执行相同的操作并将它们放在一起比较