R-使用DF2的时间戳条件过滤第一个数据帧

时间:2018-12-08 09:52:03

标签: r tidyverse lubridate

DF1:

      X        Y        DateTime
1 113.8591 22.25272 2016-01-07 10:37:33
2 113.8585 22.25276 2016-01-07 10:37:43
3 113.8578 22.25270 2016-01-07 10:37:53
4 113.8572 22.25265 2016-02-01 11:34:03
5 113.8565 22.25260 2016-02-18 12:20:13
6 113.8559 22.25251 2016-02-18 12:20:23

structure(list(Date = c("2016-10-27", "2016-10-27", "2016-10-27", 
"2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", 
"2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", 
"2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", "2016-10-27", 
"2016-10-27", "2016-10-27"), DateTime = structure(c(1477560813, 
1477560823, 1477560833, 1477560843, 1477560853, 1477560863, 1477560873, 
1477560883, 1477560893, 1477560903, 1477560913, 1477560923, 1477560933, 
1477560943, 1477560953, 1477560963, 1477560973, 1477560983, 1477560993, 
1477561003), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
20L), class = "data.frame", .Names = c("Date", "DateTime"))

DF2:

        DateTimeStart         DateTimeEnd
1 2016-01-07 10:37:00 2016-01-07 10:51:00
2 2016-01-07 10:57:00 2016-01-07 11:14:00
3 2016-01-07 11:36:00 2016-01-07 11:40:00
4 2016-01-07 11:49:00 2016-01-07 12:04:00
5 2016-01-08 12:19:00 2016-01-08 12:35:00
6 2016-02-18 11:51:00 2016-02-18 12:26:00

structure(list(DateTimeStart = structure(c(1477560960, 1477568880, 
1477569780, 1477570500, 1477571460, 1477572240, 1477572720, 1477574700, 
1477575300, 1477575960, 1477579260), tzone = "UTC", class = c("POSIXct", 
"POSIXt")), DateTimeEnd = structure(c(1477561560, 1477569360, 
1477570260, 1477571100, 1477572000, 1477572660, 1477573920, 1477575180, 
1477575840, 1477576680, 1477579920), tzone = "UTC", class = c("POSIXct", 
"POSIXt"))), row.names = c(NA, -11L), class = "data.frame", .Names = c("DateTimeStart", 
"DateTimeEnd"))

我想基于DF1的GPS点是否介于DF2 DateTimeStart和DateTimeEnd中的时间之间进行过滤。 对于上述情况,我想过滤掉DF1第4行,因为它不在DF2中的任何StartTime和EndTime之间。

如何在R中使用tidyverse / lubridate来做到这一点? 非常感谢!

2 个答案:

答案 0 :(得分:0)

定义助手功能

library(tidyverse)
is_in_interval <- function(x,interval_df){
  (x >= pull(interval_df,1) & x <= pull(interval_df,2)) %>% any()
}

然后过滤

DF1 %>% filter(unlist(map(DateTime, ~ unlist(is_in_interval(.x,DF2)))))

答案 1 :(得分:0)

稍微方便

DF1 %>% filter(map_lgl(DateTime, ~ unlist(is_in_interval(.x,DF2))))

map总是返回一个列表,因此我们需要unlist来获得一个向量。 map_lgl返回布尔向量。