问题
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"))
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.
How to do this with tidyverse/lubridate in R? Many thanks!
回答1:
Define a helper function
library(tidyverse)
is_in_interval <- function(x,interval_df){
(x >= pull(interval_df,1) & x <= pull(interval_df,2)) %>% any()
}
and then filter
DF1 %>% filter(unlist(map(DateTime, ~ unlist(is_in_interval(.x,DF2)))))
回答2:
Slightly more convenient
DF1 %>% filter(map_lgl(DateTime, ~ unlist(is_in_interval(.x,DF2))))
map
always returns a list, therefore we needed unlist
to get a vector. map_lgl
returns a vector of booleans.
来源:https://stackoverflow.com/questions/53681333/r-filter-1st-dataframe-with-conditions-of-timestamp-from-df2