[英]Merge two datasets based on certain conditions, while maintaining specific columns
客觀的
我有兩個數據集,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
格式並僅選擇End
和Sent
之間的差異小於 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.