我想根据ID和时间范围合并两个数据帧。见下文。
data1 data2
ID Unit DT1 DT2 ID EventDT
ABC 5C 1/1/2018 3/25/2018 ABC 2/2/2018
ABC 3B 6/27/2018 12/31/2018 ABC 3/21/2018
ABC 5C 2/24/2019 3/10/2019 ABC 4/4/2018
ABC 2/2/2019
datafinal
ID Unit DT1 DT2 EventDT
ABC 5C 1/1/2018 3/25/2018 2/2/2018
ABC 5C 1/1/2018 3/25/2018 3/21/2018
ABC 3B 6/27/2018 12/31/2018
ABC 5C 2/24/2019 3/10/2019 2/2/2019
我在R中寻找一种简单的方法来做,却找不到答案。我以前是Stata用户,在Stata中做到这一点的方法是使用rangejoin命令:rangejoin EventDT DT1 DT2 using data2, by(ID)
。
我将不胜感激!
data1 <- data.table(ID =c("ABC", "ABC", "ABC"),
type =c("5C", "3B", "5C"),
DT1 = c('1/1/2018', '6/27/2018', '2/24/2019'),
DT2 = c('3/25/2018','12/31/2018','3/10/2019'))
data2 <- data.table(ID =c("ABC", "ABC", "ABC", "ABC"),
EventDT = c('2/2/2018', '3/21/2018', '4/4/2018', "2/2/2019"))