[英]How to compare a DateTime in one Dataframe to a Start and End Time in Another Data frame using tidy R?
I have a dataframe of conditions that are time based.我有一个基于时间的条件的 dataframe。 I would like to compare the time in a set of data to the start and end times in the conditions to give the correct condition.我想将一组数据中的时间与条件中的开始和结束时间进行比较,以给出正确的条件。 I was thinking of using purrr to map a function to do this, but I'm stuck.我正在考虑使用 purrr 到 map 和 function 来执行此操作,但我被卡住了。
The data and an example output are below:数据和示例 output 如下:
>library(tidyverse)
>library(lubridate)
>conditions <- tibble(Condition=c("Startup","Precondition","Heating Up","Exposure","Postcondition"),
Start=ymd_hms(c("2021-12-22 19:05:00","2021-12-22 19:26:00","2021-12-22 19:35:00",
"2021-12-22 19:39:30","2021-12-22 20:04:30")),
End=ymd_hms(c("2021-12-22 19:26:00","2021-12-22 19:35:00","2021-12-22 19:39:30",
"2021-12-22 20:04:30","2021-12-22 22:09:30"))
)
>data <- tibble(DateTime=ymd_hms(c("2021-12-22 19:05:00","2021-12-22 19:05:30","2021-12-22 19:06:00",
"2021-12-22 19:06:30","2021-12-22 19:07:00","2021-12-22 19:07:30")),
R57827=c(21.1,20.8,20.7,20.5,20.4,20.3))
> conditions
# A tibble: 5 x 3
Condition Start End
<chr> <dttm> <dttm>
1 Startup 2021-12-22 19:05:00 2021-12-22 19:26:00
2 Precondition 2021-12-22 19:26:00 2021-12-22 19:35:00
3 Heating Up 2021-12-22 19:35:00 2021-12-22 19:39:30
4 Exposure 2021-12-22 19:39:30 2021-12-22 20:04:30
5 Postcondition 2021-12-22 20:04:30 2021-12-22 22:09:30
> head(data)
# A tibble: 6 x 8
DateTime R57827
<dttm> <dbl>
1 2021-12-22 19:05:00 21.1
2 2021-12-22 19:05:30 20.8
3 2021-12-22 19:06:00 20.7
4 2021-12-22 19:06:30 20.5
5 2021-12-22 19:07:00 20.4
6 2021-12-22 19:07:30 20.3
What I'm trying to do is get the following:我想要做的是得到以下内容:
> head(data)
# A tibble: 6 x 8
DateTime R57827 Condition
<dttm> <dbl> <chr>
1 2021-12-22 19:05:00 21.1 Startup
2 2021-12-22 19:26:30 20.8 Precondition
3 2021-12-22 19:35:00 20.7 Precondition
4 2021-12-22 19:35:30 20.5 Heating Up
5 2021-12-22 19:45:00 20.4 Exposure
6 2021-12-22 20:05:30 20.3 Postcondition
My brain has given up.我的大脑已经放弃了。 Can someone point me in the right direction?有人可以指出我正确的方向吗?
Thank you kindly!非常感谢你!
Shawn Way肖恩路
Using fuzzyjoin
package may help -使用模糊连接fuzzyjoin
可能会有所帮助 -
fuzzyjoin::fuzzy_inner_join(data, conditions,
by = c('DateTime' = 'Start', 'DateTime' = 'End'),
match_fun = c(`>=`, `<=`))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.