【问题标题】:R: "Fuzzy Match" and "Between" StatementsR:“模糊匹配”和“之间”语句
【发布时间】:2022-01-08 15:58:56
【问题描述】:

我正在使用 R 编程语言。我有以下表格(注意:所有变量都显示为“因素”):

table_1 = data.frame(id = c("123", "123", "125", "C125-B"), 
date_1 = c("2010-01-31","2010-01-31", "2016-01-31", "2018-01-31" ))

table_1$id = as.factor(table_1$id)
table_1$date_1 = as.factor(table_1$date_1)

table_2 = data.frame(id = c("5123", "123 A", "125", "125"), 
date_2 = c("2009-01-31","2010-01-31", "2010-01-31", "2010-01-31" ),
date_3 = c("2011-01-31","2010-01-31", "2020-01-31", "2020-01-31" ))


table_2$id = as.factor(table_2$id)
table_2$date_2 = as.factor(table_2$date_2)
table_2$date_3 = as.factor(table_2$date_3)


> table_1
      id     date_1
1    123 2010-01-31
2    123 2010-01-31
3    125 2016-01-31
4 C125-B 2018-01-31

 table_2
     id     date_2     date_3
1  5123 2009-01-31 2011-01-31
2 123 A 2010-01-31 2010-01-31
3   125 2010-01-31 2020-01-31
4   125 2010-01-31 2020-01-31

我正在尝试在以下条件下“加入”(例如内部联接)此表:

1) if table_1$id "fuzzy equal" table_2$id

2) if table_1$date BETWEEN(table_2$date_2,table_2$date_3)

我尝试在 R 中编写以下代码来做到这一点:

library(fuzzyjoin)
stringdist_inner_join(table_1, table_2,
                      by ="id", distance_col = NULL)

问题:但我不确定stringdist_inner_join 函数是否可以适应这种“介于”逻辑。

有人可以告诉我如何做到这一点吗?在 R 中还有其他方法可以实现这一点吗?

谢谢!

【问题讨论】:

  • 把你的日期变成因素的目的是什么?这不会使按时间顺序比较它们变得更加困难吗?
  • @Jon Spring:谢谢你的回复!我最初设置的日期是因素。

标签: sql r join data-manipulation fuzzy-logic


【解决方案1】:

这个怎么样?如果日期存储为日期,我们可以执行 stringdist_inner_join 并在之后进行过滤。对于大多数数据,这应该足够高效,如果不是,您可能应该使用 data.table 而不是模糊连接。

library(fuzzyjoin)
library(dplyr)
table_1$date_1 = as.Date(table_1$date_1)
table_2$date_2 = as.Date(table_2$date_2)
table_2$date_3 = as.Date(table_2$date_3)
stringdist_inner_join(table_1, table_2, by = "id", max_dist = 2) %>%
  filter(date_1 >= date_2, date_1 <= date_3)


   id.x     date_1  id.y     date_2     date_3
1   123 2010-01-31  5123 2009-01-31 2011-01-31
2   123 2010-01-31 123 A 2010-01-31 2010-01-31
3   123 2010-01-31   125 2010-01-31 2020-01-31
4   123 2010-01-31   125 2010-01-31 2020-01-31
5   123 2010-01-31  5123 2009-01-31 2011-01-31
6   123 2010-01-31 123 A 2010-01-31 2010-01-31
7   123 2010-01-31   125 2010-01-31 2020-01-31
8   123 2010-01-31   125 2010-01-31 2020-01-31
9   125 2016-01-31   125 2010-01-31 2020-01-31
10  125 2016-01-31   125 2010-01-31 2020-01-31

【讨论】:

  • @Jon Spring:谢谢你的回答!你能解释一下为什么“max_dist = 2”吗?谢谢!
  • 为什么字体是绿色的?
  • 我只是在为您的数据猜测一个合适的值(这也是默认值,因此无需指定)。
  • @jay.sf,我不知道!我不认为我做了什么不同的事情,很好奇是什么触发了它。
  • @Jon Spring:如果有时间,可以看看我的其他问题吗?
猜你喜欢
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多