如何从POSIXct列字段中获取下表中第一个和最后一个状态为“Dry”的条目的开始和结束日期?
dat <- data.frame(
Timestamp = as.POSIXct(
c(
"2021-07-30 19:00:00", "2021-07-30 19:30:00", "2021-07-30 20:00:00",
"2021-07-30 20:30:00", "2021-07-30 21:00:00", "2021-07-30 21:30:00",
"2021-07-30 22:00:00", "2021-07-30 22:30:00", "2021-07-30 23:00:00",
"2021-07-30 23:30:00", "2021-07-31 00:00:00", "2021-07-31 00:30:00",
"2021-07-31 01:00:00", "2021-07-31 01:30:00", "2021-07-31 02:00:00",
"2021-07-31 02:30:00", "2021-07-31 03:00:00", "2021-07-31 03:30:00",
"2021-07-31 04:00:00", "2021-07-31 04:30:00", "2021-07-31 05:00:00",
"2021-07-31 05:30:00", "2021-07-31 06:00:00", "2021-07-31 06:30:00",
"2021-07-31 07:00:00", "2021-07-31 07:30:00", "2021-07-31 08:00:00",
"2021-07-31 08:30:00", "2021-07-31 09:00:00", "2021-07-31 09:30:00",
"2021-07-31 10:00:00", "2021-07-31 10:30:00", "2021-07-31 11:00:00",
"2021-07-31 11:30:00", "2021-07-31 12:00:00"
)
),
State = rep(c("Dry", "Wet", "Dry", "Wet", "Dry"), c(6L, 8L, 8L, 8L, 5L))
)
字符串
预期产出如下
data.frame(
From = as.POSIXct(c("2021-07-30 19:00:00", "2021-07-31 02:00:00", "2021-07-31 10:00:00")),
To = as.POSIXct(c("2021-07-30 21:30:00", "2021-07-31 05:30:00", "2021-07-31 12:00:00"))
)
我尝试了使用dqr进行分组,但不确定如何进一步进行,尝试的代码如下所示
library(dplyr)
sms_data %>%
group_by(State)
谢谢
1条答案
按热度按时间yzckvree1#
您可以利用
factor
的整数结构为每组 dry 和 wet 分配一个递增的整数值。然后,使用by
,拆分并应用range
,rbind
并转换as.POSIXct
,最后在rle
的帮助下转换cbind
状态列。字符串