首页 > 解决方案 > 有没有办法通过将一列单词与 R 中的一列句子匹配来合并

问题描述

例如:

a<-c("This sentence has San-Francisco","This one has london","This one has newYork")
b<-c(10,20,30)

data1<-as.data.frame(cbind(a,b))

c<-c("San Francisco","London", "New York")
d<-c(100,2050,100)

data2<-as.data.frame(cbind(c,d))

所以我想将数据 1 与数据 2 合并,特别是通过将a列与c列匹配。问题是城市名称的拼写不同,句子通常包含不同点的城市名称。我试过使用 fuzzjoin 包,但我得到的匹配很少。有没有办法自动化这个?基本上我想得到

这个

标签: rdplyrfuzzyjoin

解决方案


您可以清理数据以使事情变得更容易,在这里使用stringr(有很多可能的方法):

我在这里所做的是删除所有标点符号、大写字母和空格a,然后对c. 使用字符串ac因此简化后,可以更轻松地提取它们之间的匹配项(我的变量city)并加入。

library(stringr)
library(dplyr)
library(purrrr)
a <-
  c(
    "This sentence has San-Francisco",
    "This one has london",
    "This one has newYork",
    "Here also San Francisco"
  )
a_test <- str_replace_all(a, " ", "")
a_test <- str_replace_all(a_test, "[:punct:]", "")
a_test <- str_to_lower(a_test)

b <- c(10, 20, 30, 40)

c <- c("San Francisco", "London", "New York")
c_test <- str_replace_all(c, " ", "")
c_test <- str_to_lower(c_test)

d <- c(100, 2050, 100)

city <- map(a_test, str_extract, c_test) %>%
  unlist() %>%
  na.omit()

data1 <- as.data.frame(cbind(a, city, b))

data2 <- as.data.frame(cbind(c, c_test, d))

inner_join(data1, data2, by = c("city" = "c_test")) %>%
  dplyr::select(a, b, c, d)
1 This sentence has San-Francisco 10 San Francisco  100
2             This one has london 20        London 2050
3            This one has newYork 30      New York  100
4         Here also San Francisco 40 San Francisco  100

推荐阅读