Merge nearest date, and related variables from a another dataframe by group

后端 未结 4 1197
花落未央
花落未央 2020-12-03 08:57

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

4条回答
  •  广开言路
    2020-12-03 09:03

    We can also do this by one-liner with 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))
    

提交回复
热议问题