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

时间:2015-04-16 16:03:35

标签: r date time intervals calculated-columns

我有一个像这样的数据框

    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)

但要大得多,需要从时间的开始创建30秒的阶段,这是&#34; 2014-05-01 11:36:12&#34;直到最后,为了根据时间找到speed1和speed2的平均值。

我需要以这种形式获得

      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")

1 个答案:

答案 0 :(得分:2)

我们可以使用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