首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用stringdist_join对两个数据帧进行分组和循环

使用stringdist_join对两个数据帧进行分组和循环
EN

Stack Overflow用户
提问于 2021-01-06 22:04:14
回答 1查看 20关注 0票数 0

我想使用stringdist_join按十年对美国的各个县进行模糊匹配。由于县名称会随着时间的推移而变化,因此我希望在每十年匹配到正确的县名称。

如果我写道:

代码语言:javascript
复制
stringdist_join(mispelled,correct,by=c('decade','county'))

然后,stringdist_join也会对十年进行模糊匹配,例如1960年到1970年,而实际上我希望将十年变量视为正确的,并且只模糊匹配县。

我可以看到,我需要按十年对拼写错误和更正的数据帧进行分组,然后分别在每个数据帧上运行,但我不知道如何做到这一点。Tidyverse解决方案将是首选。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-06 22:21:12

归根结底,我认为您寻求的方法是允许max_dist作为距离的向量,您可以使用stringdist_inner_join(..., max_dist=c(0,2))。不幸的是,虽然这已经被要求(在2017年:https://github.com/dgrtwo/fuzzyjoin/issues/36https://github.com/dgrtwo/fuzzyjoin/issues/21),但它似乎还没有实现。

如果您负担得起更大的中间连接产品,一种变通方法是允许它,然后过滤掉decade是不精确连接的地方。

由于缺乏数据,我将使用ggplot2::diamonds进行演示。在这里,我需要cut的普通stringdist功能和clarity的精确匹配。

代码语言:javascript
复制
d <- data.frame(cut = c("Idea", "Premiums", "Premioom", "VeryGood", "VeryGood", "Faiir"),
                clarity = rep(c("SI1", "SI2"),3),
                type = 1:6)
data("diamonds", package = "ggplot2")
diamonds <- diamonds[1:10,]

joined <- stringdist_inner_join(diamonds, d, by = c("cut", "clarity"))
joined
# # A tibble: 8 x 13
#   carat cut.x     color clarity.x depth table price     x     y     z cut.y    clarity.y  type
#   <dbl> <ord>     <ord> <ord>     <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>    <chr>     <int>
# 1 0.23  Ideal     E     SI2        61.5    55   326  3.95  3.98  2.43 Idea     SI1           1
# 2 0.21  Premium   E     SI1        59.8    61   326  3.89  3.84  2.31 Premiums SI2           2
# 3 0.21  Premium   E     SI1        59.8    61   326  3.89  3.84  2.31 Premioom SI1           3
# 4 0.290 Premium   I     VS2        62.4    58   334  4.2   4.23  2.63 Premiums SI2           2
# 5 0.26  Very Good H     SI1        61.9    55   337  4.07  4.11  2.53 VeryGood SI2           4
# 6 0.26  Very Good H     SI1        61.9    55   337  4.07  4.11  2.53 VeryGood SI1           5
# 7 0.22  Fair      E     VS2        65.1    61   337  3.87  3.78  2.49 Faiir    SI2           6
# 8 0.23  Very Good H     VS1        59.4    61   338  4     4.05  2.39 VeryGood SI1           5

subset(joined, clarity.x == clarity.y)
# # A tibble: 2 x 13
#   carat cut.x     color clarity.x depth table price     x     y     z cut.y    clarity.y  type
#   <dbl> <ord>     <ord> <ord>     <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>    <chr>     <int>
# 1  0.21 Premium   E     SI1        59.8    61   326  3.89  3.84  2.31 Premioom SI1           3
# 2  0.26 Very Good H     SI1        61.9    55   337  4.07  4.11  2.53 VeryGood SI1           5
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65597213

复制
相关文章

相似问题

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