Join two data frames in R based on closest timestamp

前端 未结 2 1532
终归单人心
终归单人心 2020-11-30 05:56

Hi I have two tables (table1 and table2 below) and would like to join them based on the closest timestamp to form expected_output. Some kind of solution involving dplyr wou

2条回答
  •  粉色の甜心
    2020-11-30 06:53

    Using rolling joins feature of data.table with roll = "nearest":

    require(data.table) # v1.9.6+
    setDT(table1)[, val2 := setDT(table2)[table1, val2, on = "date", roll = "nearest"]]
    

    Here, val2 column is created by performing a join on the column date with roll = "nearest" option. For each row of table1$date, the closest matching row from table2$date is computed, and val2 for corresponding row is extracted.

提交回复
热议问题