在数据框的一列中创建连续的时间阶段

Create consecutive phases of time in one column of a data frame

我有一个这样的数据框

    time<-c("2014-05-01 11:36:12", "2014-05-01 11:36:14", "2014-05-01 11:36:15",
          "2014-05-02 11:37:16", "2014-05-02 11:39:16", "2014-05-02 11:39:17")
    speed1<-c( 8, 8.9,8.2, 9, 9, 8.9)
    speed2<-c(4,5,6,2,4,1)

 d<-data.frame(time,speed1,speed2)

但更大,需要创建从时间“2014-05-01 11:36:12”开始到结束的 30 秒的阶段,以便找到速度 1 和速度 2 的平均值时间。

我需要得到这个表格的col

      timenew<-c("2014-05-01 11:36:12", "2014-05-01 11:36:12", "2014-05-01 11:36:12",
          "2014-05-02 11:37:16", "2014-05-02 11:39:16", "2014-05-02 11:39:16")

我们可以使用 cut

 d$time <- as.POSIXct(d$time)
 ind <- seq(d$time[1], d$time[nrow(d)]+60, by = '30 sec')

 library(dplyr)
 d %>%
    group_by(time1 = cut(time, breaks=ind)) %>%
    mutate(timenew = time[1]) %>%
    ungroup() %>%
    select(-time1)
  #                 time speed1 speed2             timenew
  #1 2014-05-01 11:36:12    8.0      4 2014-05-01 11:36:12
  #2 2014-05-01 11:36:14    8.9      5 2014-05-01 11:36:12
  #3 2014-05-01 11:36:15    8.2      6 2014-05-01 11:36:12
  #4 2014-05-02 11:37:16    9.0      2 2014-05-02 11:37:16
  #5 2014-05-02 11:39:16    9.0      4 2014-05-02 11:39:16
  #6 2014-05-02 11:39:17    8.9      1 2014-05-02 11:39:16