R-使用DF2的时间戳条件过滤第一个数据帧 [英] R - Filter 1st Dataframe with conditions of timestamp from DF2

查看:90
本文介绍了R-使用DF2的时间戳条件过滤第一个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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行,因为它不属于任何StartTime& DF2中的EndTime.

I would like to do filtering for GPS point from DF1 based on whether it falls between the time in each of the DF2 DateTimeStart and DateTimeEnd. For the above case, I would like to filter out DF1 row 4 since it didn't fall between any of the StartTime & EndTime in DF2.

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

How to do this with tidyverse/lubridate in R? Many thanks!

推荐答案

定义助手功能

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)))))

这篇关于R-使用DF2的时间戳条件过滤第一个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆