问题描述
我有几个包含字符的相当大的数据表,我想将它们与我的数据库中的条目连接起来。拼写通常不太正确,因此无法加入。 我知道没有办法创建一个同义词表来替换一些拼写错误的字符。但是有没有办法自动检测某些异常(见下面的例子)?
我的数据表看起来像这样:
data <- data.table(products=c("potatoe Chips","potato Chips","potato chips","Potato-chips","apple","Apple","Appl","Apple gala"))
我的数据库中的字符是这样的:
characters.database <- data.table(products=c("Potato Chips","Potato Chips Paprika","Apple"),ID=c("1","2","3"))
目前如果我执行 left_join 只有“Apple”会加入:
data <- data %>%
left_join(characters.database,by = c('products'))
结果:
产品 | ID |
---|---|
薯片 | 不适用 |
薯片 | 不适用 |
薯片 | 不适用 |
薯片 | 不适用 |
苹果 | 不适用 |
苹果 | 3 |
应用 | 不适用 |
苹果晚会 | 不适用 |
是否可以在 left_join 期间自动忽略:“大小写字母”、空格“”、“-”和单词末尾的“e”?
这将是我想要的桌子:
产品 | ID |
---|---|
薯片 | 1 |
potatochips | 1 |
薯片 | 1 |
薯片 | 1 |
苹果 | 1 |
苹果 | 3 |
应用 | 1 |
苹果晚会 | 不适用 |
有什么想法吗?
解决方法
如果我是你,我会做一些事情:
- 我会去除所有特殊字符,小写所有字符,删除空格等。这会有所帮助(即薯片、薯片和薯片都转到“potatochips”,然后您可以加入上)。
- 有一个名为
fuzzyjoin
的包,可让您加入正则表达式、编辑距离等。这将有助于解决Apple
与Apple Gala
和拼写错误等问题。立>
你可以去掉特殊字符(只保留字母)+小写,比如:
library(stringr)
library(magrittr)
string %>%
str_remove_all("[^A-Za-z]+") %>%
tolower()
,
感谢 Matt Kaye 的建议,我现在做了类似的事情。 由于我需要在数据库中正确拼写,并且我的某些字符包含相关的符号和数字,因此我执行了以下操作:
#data
data <- data.table(products=c("potatoe Chips","potato Chips","potato chips","Potato-chips","apple","Apple","Appl","Apple Gala"))
characters.database <- data.table(products=c("Potato Chips","Potato Chips Paprika","Apple"),ID=c("1","2","3"))
#remove spaces and capital letters in data
data <- data %>%
mutate(products= tolower(products)) %>%
mutate(products= gsub(" ","",products))
#add ID to database
characters.database <- characters.database %>%
dplyr::mutate(ID = row_number())
#remove spaces and capital letters in databasr product names
characters.database_syn <- characters.database %>%
mutate(products= tolower(products)) %>%
mutate(products= gsub(" ",products))
#join and add correct spelling from database
data <- data %>%
left_join(characters.database_syn,by = c('products')) %>%
select(product_syn=products,'ID') %>%
left_join(characters.database,by = c('ID'))
#other synonyms have to manually be corrected or with the help of a synonym table (As in MY data special caracters are relevant!)