如果你有大数据,我建议使用 data.tables滚动连接 instead
假设这些是您的数据集
dfa <- read.table(text = "ID Date
42 '2012-07-21'
42 '2013-04-12'", header = TRUE)
dfb <- read.table(text = "ID Date
12 '2016-09-08'
35 '2008-02-02'
42 '2012-01-09'
42 '2013-03-13'", header = TRUE)
我们将它们转换为 data.tables 并转换Date
列至IDate
class
library(data.table) #1.9.8+
setDT(dfa)[, Date := as.IDate(Date)]
setDT(dfb)[, Date := as.IDate(Date)]
然后,只需加入即可(您可以双向进行滚动加入)
# You can perform another rolling join for `roll = -180` too
indx <- dfb[
dfa, # Per each row in dfa find a match in dfb
on = .(ID, Date), # The columns to join by
roll = 180, # Rolling window, can join again on -180 afterwards
which = TRUE, # Return the row index within `dfb` that been matched
mult = "first", # Multiple match handling- take only the first match
nomatch = 0L # Don't return unmatched indexes (NAs)
]
dfb[indx]
# ID Date
# 1: 42 2013-03-13
实现此目的的另一种方法是使用 data.tablesnon-equi加入功能日期+-180(手动创建)列
# Create range columns
dfa[, c("Date_m_180", "Date_p_180") := .(Date - 180L, Date + 180L)]
# Join away
indx <- dfb[dfa,
on = .(ID, Date >= Date_m_180, Date <= Date_p_180),
which = TRUE,
mult = "first",
nomatch = 0L]
dfb[indx]
# ID Date
# 1: 42 2013-03-13
两种方法都应该几乎立即处理大型数据集