I have two dataframes each with multiple rows per ID. I need to return the closest date and related data from the second dataframe based on the ID and date of the first data
Using data.table, simple and elegant solution:
library(data.table)
setDT(df1)
setDT(df2)
setkey(df2, ID, dateTarget)[, dateMatch:=dateTarget]
df2[df1, roll='nearest']
ID dateTarget ValueMatch dateMatch Value
1: 3 2015-11-14 48 2015-07-06 47
2: 3 2015-02-22 94 2015-03-09 52
3: 1 2014-12-29 88 2014-12-06 18
4: 3 2015-12-08 48 2015-07-06 98
5: 2 2013-01-14 77 2013-04-08 52
6: 2 2015-07-29 68 2015-08-01 97
7: 3 2013-05-30 85 2013-04-01 91
8: 1 2013-11-04 35 2014-02-21 70
9: 2 2015-06-15 68 2015-08-01 98
10: 3 2014-11-17 95 2014-12-15 68