我有两个数据框,我想根据时间戳合并它们,但保留所有时间戳。实质上,是将每个med时间戳(数据帧a)与之前和之后的所有实验室时间戳(数据帧b)进行组合,直到下一个med时间戳。
我已经尝试过合并它们并进行滚动联接。
我想将数据框a与数据框b合并以获得数据框c。
a<-data.frame("Patient" = c(rep("A", times = 2)),"Med_Time" = c(as.POSIXct("2018-05-11 10:37"), as.POSIXct("2018-05-12 17:16")))
b<-data.frame("Patient" = c(rep("A", times = 13)),"Lab_Time" = c(as.POSIXct("2018-05-11 02:15:00"),
as.POSIXct("2018-05-11 06:25:00"),
as.POSIXct("2018-05-11 12:45:00"),
as.POSIXct("2018-05-11 16:51:00"),
as.POSIXct("2018-05-11 21:51:00"),
as.POSIXct("2018-05-12 05:46:00"),
as.POSIXct("2018-05-12 12:42:00"),
as.POSIXct("2018-05-12 17:09:00"),
as.POSIXct("2018-05-12 21:16:00"),
as.POSIXct("2018-05-13 06:04:00"),
as.POSIXct("2018-05-13 10:45:00"),
as.POSIXct("2018-05-13 16:02:00"),
as.POSIXct("2018-05-13 21:40:00")),"Lab_Res" = c(70,80,122,180,161,170,210,212,278,156,172,174,165))
c<-data.frame("Patient" = c(rep("A", times = 13)),"Med_Time" = c(rep(as.POSIXct("2018-05-11 10:37:00"), times = 8),
rep(as.POSIXct("2018-05-12 17:16:00"), times = 5)),"Lab_Time" = c(as.POSIXct("2018-05-11 02:15:00"),
as.POSIXct("2018-05-11 06:25:00"),
as.POSIXct("2018-05-11 12:45:00"),
as.POSIXct("2018-05-11 16:51:00"),
as.POSIXct("2018-05-11 21:51:00"),
as.POSIXct("2018-05-12 05:46:00"),
as.POSIXct("2018-05-12 12:42:00"),
as.POSIXct("2018-05-12 17:09:00"),
as.POSIXct("2018-05-12 21:16:00"),
as.POSIXct("2018-05-13 06:04:00"),
as.POSIXct("2018-05-13 10:45:00"),
as.POSIXct("2018-05-13 16:02:00"),
as.POSIXct("2018-05-13 21:40:00")),"Lab_Res" = c(70,80,122,180,161,170,210,212,278,156,172,174,165))
任何见解都会有所帮助!谢谢!
答案 0 :(得分:1)
我们可以使用data.table
联接
library(data.table)
setDT(a)[setDT(b)[, .(Patient, Med_Time = Lab_Time, Lab_Time, Lab_Res)],
on = .(Patient, Med_Time), roll = -Inf]