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
We can also do this by one-liner with dplyr.
dplyr
library(dplyr) left_join(df1, df2, by = "ID") %>% mutate(dateDiff = abs(dateTarget.x - dateTarget.y)) %>% group_by(ID, dateTarget.x) %>% filter(dateDiff == min(dateDiff))