【问题标题】:Combine two datasets with Interval time condition in R (I would like to avoid combinations and just have unique matches)将两个数据集与 R 中的间隔时间条件相结合(我想避免组合并且只有唯一匹配)
【发布时间】:2020-06-06 05:37:27
【问题描述】:

我有两个独立的数据集:df1 和 df2。我想创建一个新的数据集 df3,如果日期时间在 20 秒内,它将匹配 df1 的 endtime 列和 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)

【问题讨论】:

标签: r datatable dplyr lubridate


【解决方案1】:

可能是,我们需要在转换为DateTime 类之后再做一个crossingfilter

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

【讨论】:

  • 好的,谢谢 Akrun,这会排除任何重复项吗?
  • @TanishaHudson 可以在末尾添加%&gt;% distinct
  • 好吧,我在发送的行中得到了重复的值,因为不止一个 endtime 与相同的发送值匹配
  • @TanishaHudson crossing 对“endtime”的每个值与“sent”的值进行完全扩展。如果您需要通过特定的 coumn 获得不同的值,请使用 distinct(sent, .keep_all = TRUE)
  • @TanishaHudson 是的,如果您创建了一个对象,那么使用原始数据执行anti_join 可以获得其他行
猜你喜欢
  • 2020-06-06
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多