根据特定条件合并两个数据集,同时维护特定列

Merge two datasets based on certain conditions, while maintaining specific columns

Objective

我有两个数据集,df1 和 df2。我想合并两者,只有当它们的日期时间值在彼此相差 20 秒内匹配时。我还想将 Duration 列保留在 df2 列中

  df1 

  End                           Duration

  1/22/2020 5:42:13 AM          34
  1/30/2020 12:12:50 AM          5


  df2

  Sent

  1/22/2020 5:42:20 AM
  1/31/2020 12:00:00 PM

期望的输出:

  End                                 Sent                       Duration


  1/22/2020 5:42:13 AM               1/22/2020 5:42:20 AM        34

输入:

 df1


 structure(list(End = structure(1:2, .Label = c("1/22/2020 5:42:13 AM", 
 "1/30/2020 12:12:50 AM"), class = "factor"), Duration = c(34L, 
 5L)), class = "data.frame", row.names = c(NA, -2L))


df2

structure(list(Sent = structure(1:2, .Label = c("1/22/2020 5:42:20 AM", 
"1/31/2020 12:00:00 PM"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

我试过的

df3<-crossing(endtime = as.POSIXct(df1$End,format ="%m/%d/%Y %I:%M:%S %p" ), 
SentTime = as.POSIXct(df2$Sent, format = "%m/%d/%Y %I:%M:%S %p")) %>% 
filter((endtime - seconds(20)) <= SentTime, 
      (endtime + seconds(20)) >= (SentTime)) %>%
mutate_all(format, format = "%m/%d/%Y %I:%M:%S %p") %>%
distinct(SentTime, .keep_all = TRUE)

上面的代码很好地匹配了20秒以内的日期时间,但是没有相应的持续时间列。如果这些数据集彼此之间的间隔在 20 秒以内,我该如何匹配这些数据集,同时还保持相应的 Duration 列?

欢迎任何建议。

我们可以使用 crossing 创建所有可能的组合,将列更改为 POSIXct 格式,并且 select 仅 End 和 [=14= 之间存在差异的行]不到20秒。

library(dplyr)

tidyr::crossing(df1, df2) %>%
  mutate_at(vars(End, Sent), lubridate::mdy_hms) %>%
  filter(abs(as.numeric(difftime(End, Sent, "seconds"))) < 20)

# A tibble: 1 x 3
#  End                 Duration Sent               
#  <dttm>                 <int> <dttm>             
#1 2020-01-22 05:42:13       34 2020-01-22 05:42:20