dplyr - 根据日期差异连接表

dplyr - Join tables based on a date difference

太晚了,我想不通。我正在使用 lubridate 和 dlypr。

我的数据如下:
table1 = 每个受试者 1 次观察,有日期

table2= 每个对象有 1 次或更多次观察以及相关日期

当我离开加入时,我实际上添加了观察。这是因为我在 table 2 中有多个记录与键匹配。我怎样才能简单地将其设为条件连接,以便仅连接来自 table 2 的 1 条匹配记录,因为它的日期最接近 table 1 中的日期。

对不起,如果这很冗长。

使用data.table-套餐加入。使用 roll = "nearest" 获得最近的匹配..

library(data.table)
dt1 <- data.table( id = 1:10, date = 1:10, stringsAsFactors = FALSE )
dt2 <- data.table( date = 6:15, letter = letters[1:10], stringsAsFactors = FALSE )

dt1[, letter := dt2[dt1, letter, on = "date", roll = "nearest"] ][]

#    id date letter
# 1:  1    1      a
# 2:  2    2      a
# 3:  3    3      a
# 4:  4    4      a
# 5:  5    5      a
# 6:  6    6      a
# 7:  7    7      b
# 8:  8    8      c
# 9:  9    9      d
# 10: 10   10     e