将两个数据集与 R 中的间隔时间条件结合起来(我想避免组合,只进行唯一匹配)

Combine two datasets with Interval time condition in R (I would like to avoid combinations and just have unique matches)

我有两个独立的数据集:df1 和 df2。我想创建一个新的数据集 df3,如果日期时间彼此相差 20 秒以内,它将 df1 的结束时间列与 df2 的发送列相匹配。

 df1

 endtime                     ID

 1/7/2020  1:35:08 AM         A
 1/7/2020  1:39:00 AM         B
 1/20/2020 1:45:00 AM         C



 df2

sent                         ID

1/7/2020  1:35:20 AM          E
1/7/2020  1:42:00 AM          F
1/20/2020 1:55:00 AM          G
1/20/2020 2:00:00 AM          E

这是我想要的 df3 输出。只有一行,因为只有两个值符合 endtime 和 sent 列在 20 秒内的条件。我想要独特的比赛,而不是组合。本质上是一个带有时间条件的合并。

endtime                  sent 

1/7/2020 1:35:08 AM      1/7/2020  1:35:20 AM       

这是输出:

df1

structure(list(endtime = structure(c(2L, 3L, 1L), .Label = c("1/10/2020 1:45:00 AM", 
"1/7/2020 1:35:08 AM", "1/7/2020 1:39:00 AM"), class = "factor"), 
ID = structure(1:3, .Label = c("A", "B", "C"), class = "factor")), class = "data.frame", row.names =   c(NA, 
 -3L))





 df2

 structure(list(sent = structure(c(3L, 4L, 1L, 2L), .Label = c("1/20/2020 1:55:00 AM", 
 "1/20/2020 2:00:00 AM", "1/7/2020 1:35:20 AM", "1/7/2020 1:42:00 AM"
 ), class = "factor"), ID = structure(c(1L, 2L, 3L, 1L), .Label = c("E", 
"F", "G"), class = "factor")), class = "data.frame", row.names = c(NA, 
-4L))

这是我试过的:

我正在考虑执行左连接并匹配值,或者我可以使用 merge(),但棘手的部分是将值与条件语句匹配。任何建议表示赞赏。

library(dplyr)
left_join(df1, df2)

可能是,我们需要做一个crossing然后转换成DateTimeclass

然后filter
library(dplyr)
library(tidyr)
library(lubridate)
crossing(endtime = as.POSIXct(df1$endtime,format ="%m/%d/%Y %I:%M:%S %p" ), 
           sent = as.POSIXct(df2$sent, format = "%m/%d/%Y %I:%M:%S %p")) %>% 
     filter((endtime - seconds(20)) <= sent, 
                 (endtime + seconds(20)) >= (sent)) %>%
     mutate_all(format, format = "%m/%d/%Y %I:%M:%S %p") %>%
     distinct
# A tibble: 1 x 2
#  endtime                sent                  
#  <chr>                  <chr>                 
#1 01/07/2020 01:35:08 AM 01/07/2020 01:35:20 AM