我正在使用 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 中還有其他方法可以實作這一點嗎?
謝謝!
uj5u.com熱心網友回復:
這個怎么樣?如果日期存盤為日期,我們可以執行 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374315.html
