基于最近的时间戳在R中连接两个数据帧

基于最近的时间戳在R中连接两个数据帧,r,dataframe,timestamp,dplyr,posixct,R,Dataframe,Timestamp,Dplyr,Posixct,您好,我有两个表(下面的表1和表2),希望根据最接近的时间戳将它们连接起来,以形成预期的_输出。如果可能的话,涉及dplyr的某种解决方案将是非常好的,但如果它使事情进一步复杂化的话,就不是这样了 table1 = structure(list(date = structure(c(1437051300, 1434773700, 1431457200 ), class = c("POSIXct", "POSIXt"), tzone = ""), val1 = c(94L, 33L, 53L)

您好,我有两个表(下面的表1和表2),希望根据最接近的时间戳将它们连接起来,以形成预期的_输出。如果可能的话,涉及dplyr的某种解决方案将是非常好的,但如果它使事情进一步复杂化的话,就不是这样了

table1 = 
structure(list(date = structure(c(1437051300, 1434773700, 1431457200
), class = c("POSIXct", "POSIXt"), tzone = ""), val1 = c(94L, 
33L, 53L)), .Names = c("date", "val1"), row.names = c(NA, -3L
), class = "data.frame")

table2 = 
structure(list(date = structure(c(1430248288, 1435690482, 1434050843
), class = c("POSIXct", "POSIXt"), tzone = ""), val2 = c(67L, 
90L, 18L)), .Names = c("date", "val2"), row.names = c(NA, -3L
), class = "data.frame")

expected_output = 
structure(list(date = structure(c(1437051300, 1434773700, 1431457200
), class = c("POSIXct", "POSIXt"), tzone = ""), val1 = c(94L,
33L, 53L), val2 = c(90L, 18L, 67L)), .Names = c("date", "val1", 
"val2"), row.names = c(NA, -3L), class = "data.frame")

这可能很慢,但是

d   <- function(x,y) abs(x-y) # define the distance function
idx <- sapply( table1$date, function(x) which.min( d(x,table2$date) )) # find matches

cbind(table1,table2[idx,-1,drop=FALSE])
#                  date val1 val2
# 2 2015-07-16 08:55:00   94   90
# 3 2015-06-20 00:15:00   33   18
# 1 2015-05-12 15:00:00   53   67

d使用
数据的滚动联接功能。表
带有
roll=“nearest”


这里,
val2
列是通过使用
roll=“nearest”
选项对列
date
执行联接而创建的。对于
table1$date
的每一行,计算
table2$date
中最接近的匹配行,并提取对应行的
val2

这非常有用!知道如何从“最近的”更改为“最近的”,即保持时间方向性,而不是将来合并到一行吗?@emudrak
roll=Inf
directive unlimited<代码>滚动=30
过期的方向限制。使用标志控制方向。
require(data.table) # v1.9.6+
setDT(table1)[, val2 := setDT(table2)[table1, val2, on = "date", roll = "nearest"]]