基于最接近的时间戳,在R中连接两个具有多个列的数据帧

基于最接近的时间戳,在R中连接两个具有多个列的数据帧,r,R,这个问题以前已经问过了。然而,只有当数据帧仅包含两个变量(其中一个是时间戳)时,问题和建议的解决方案中呈现的情况才起作用 我很惊讶,因为这个解决方案根本无法推广,它只处理一个非常具体的案例 因此,如果我们有一个数据帧df1,看起来像这样: Timestamp Var1 Var2 ... Var850 01-01-20 10:47 7 8 5 01-01-20 11:50 6 4 3 Timestamp Var851 Var85

这个问题以前已经问过了。然而,只有当数据帧仅包含两个变量(其中一个是时间戳)时,问题和建议的解决方案中呈现的情况才起作用

我很惊讶,因为这个解决方案根本无法推广,它只处理一个非常具体的案例

因此,如果我们有一个数据帧
df1
,看起来像这样:

Timestamp       Var1 Var2 ... Var850
01-01-20 10:47  7    8        5
01-01-20 11:50  6    4        3
Timestamp       Var851 Var852 ... Var2992
01-01-20 10:55  4    1            1
01-01-20 12:08  3    4            6
和一个数据帧df2,看起来像这样:

Timestamp       Var1 Var2 ... Var850
01-01-20 10:47  7    8        5
01-01-20 11:50  6    4        3
Timestamp       Var851 Var852 ... Var2992
01-01-20 10:55  4    1            1
01-01-20 12:08  3    4            6

我们如何根据最近的时间戳合并它们?

进入
数据的世界。table
的滚动联接

样本数据

#or use
#    setDT(df1); setDT(df2)
#to convert existing data.frame df1 and df2 to data.table


library( data.table)
df1 <- data.table::fread("Timestamp       Var1 Var2 
01-01-20T10:47  7    8        
01-01-20T11:50  6    4")        

df2 <- data.table::fread("Timestamp       Var851 Var852
01-01-20T10:55  4    1
01-01-20T12:08  3    4")

#timestamps/dates have to be of posix- or date-class to be able 
#to roll-join them
df1[, Timestamp := as.POSIXct( Timestamp, format = "%d-%m-%yT%H:%M")]
df2[, Timestamp := as.POSIXct( Timestamp, format = "%d-%m-%yT%H:%M")]

你找到的答案没有任何理由不适用于你的案例。我认为那里的答案也应该适用于你的案例。您只是不分配
val2:=
。假设您的
时间戳
属于
POSIXct
类。你试过了吗?你得到了什么输出?