首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >逐字和逐行比较字符串

逐字和逐行比较字符串
EN

Stack Overflow用户
提问于 2019-10-17 06:14:54
回答 2查看 56关注 0票数 1

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

“卡博街AT拉格斯街”和“卡博街拉格斯街”

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-17 06:31:24

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

代码语言:javascript
运行
复制
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

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

票数 0
EN

Stack Overflow用户

发布于 2019-10-17 06:22:29

我不确定简单地比较两个字符串中的两个以上相似的单词是否足以解决您的问题。但是,可以使用stringr包中的str_split函数以这种方式完成。我还添加了一种从比较中删除不需要的单词的方法,如"ST“和"AT":

代码语言:javascript
运行
复制
# 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.")
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58422350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档