r - 有没有办法通过将一列单词与 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 包,但我得到的匹配很少。有没有办法自动化这个?基本上我想得到
解决方案
您可以清理数据以使事情变得更容易,在这里使用stringr
(有很多可能的方法):
我在这里所做的是删除所有标点符号、大写字母和空格a
,然后对c
. 使用字符串a
并c
因此简化后,可以更轻松地提取它们之间的匹配项(我的变量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
推荐阅读
- javascript - 在不访问源代码的情况下更改动画条 HTML 的内容
- xml - XML 变量作为 OG 标签的 Razor MVC 运算符?
- r - 我想先删除文本
- python - def中没有导数的非线性Newton-Raphson?
- ruby-on-rails - 根据rails中的条件从依赖表中获取最后一条记录
- spring-boot - 如何让我的两个 docker 容器相互通信?
- python - 如何连接到数据库以提取数据并编写 pandas 数据框
- php - 如何在 Woocommerce 中将多个自定义字段传递到购物车?
- python - 如何计算两个日期之间的天数?
- kotlin - 如何从多项式表达式中获取系数?