R语言 基于循环条件从POSIXct列提取和提取到POSIXct列

sczxawaw  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(82)

如何从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)

谢谢

yzckvree

yzckvree1#

您可以利用factor的整数结构为每组 drywet 分配一个递增的整数值。然后,使用by,拆分并应用rangerbind并转换as.POSIXct,最后在rle的帮助下转换cbind状态列。

> by(dat$Timestamp, cumsum(abs(c(0, diff(as.integer(as.factor(dat$State)))))), range) |>
+   do.call(what='rbind.data.frame') |> lapply(as.POSIXct) |> as.data.frame() |>
+   setNames(c('from', 'to')) |> cbind(state=rle(dat$State)$values)
                 from                  to state
1 2021-07-30 19:00:00 2021-07-30 21:30:00   Dry
2 2021-07-30 22:00:00 2021-07-31 01:30:00   Wet
3 2021-07-31 02:00:00 2021-07-31 05:30:00   Dry
4 2021-07-31 06:00:00 2021-07-31 09:30:00   Wet
5 2021-07-31 10:00:00 2021-07-31 12:00:00   Dry

字符串

相关问题