如何在R中将时间序列数据分组为5分钟的舍入间隔? [英] How to group Time Series data into round intervals of 5 minutes in R?

查看:128
本文介绍了如何在R中将时间序列数据分组为5分钟的舍入间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的时间序列数据框:

I have a time series data frame looking like this:

  Time                 Source  Value
1 2016-01-20 15:10:04  C04     OPEN
2 2016-01-20 15:09:57  M04     true
3 2016-01-20 15:09:53  M02     true
4 2016-01-20 15:09:53  M03     true
5 2016-01-20 14:44:54  M04     true

现在我会我喜欢将它们从00:00:00开始以5分钟为间隔进行分组,这样我得到的间隔为0-5-10-15-20 ...依此类推。时间间隔稍后将用作组标识符:

now I would like to group them in intervals of 5 minutes starting from 00:00:00, so that I get intervals of 0-5-10-15-20... and so on. The intervals shall be used later as a group identifier:

  Time                 Source  Value  Group
1 2016-01-20 15:10:04  C04     OPEN   10
2 2016-01-20 15:09:57  M04     true   5
3 2016-01-20 15:09:53  M02     true   5
4 2016-01-20 15:09:53  M03     true   5
5 2016-01-20 14:44:54  M04     true   40

我已经尝试使用breaks = 5 min来cut()日期。但结果却不是这样:

I already tried to cut() the dates using breaks="5 min" but instead of getting round start and end values, the result looks like this:

 > table(cut.POSIXt(df.formatted$Time, breaks="5 min"))[1:5]
 2015-12-31 12:49:00 2015-12-31 12:54:00 2015-12-31 12:59:00 2015-12-31 13:04:00 2015-12-31 13:09:00 
              4                   0                   0                   1                  15 

有没有办法告诉cut()使用舍入时间间隔?我还尝试使用xts包进行分组,但是OHLC的困惑远不止于此。我也尝试使用heR.Misc包(请参见时间.factor文档,但是由于文档不多,我无法使其正常运行。

Is there a way to tell cut() to use round time intervals? I also tried the grouping using xts package, but got more confused by the OHLC than it helped me. Also I tried using the heR.Misc package (see time.factor documentation but due to the poor documentation I couldn't get it to run properly.

有人可能知道如何解决此问题吗?

Does someone maybe know how to solve this problem?

推荐答案

首先,您需要安装 chron软件包,该软件包具有 minutes()函数

First, you need to install "chron" package. This package has minutes() function that gives you the minute of your time.

我必须将第一列和第二列粘贴在一起,但我认为您也不必这样做,只需使用 tmpTime<-tmp [,1]

I have to paste first and second column together but i don't think you have to do too. Use just tmpTime <- tmp[,1]

library(chron)

tmp <- read.table(text="Time  Source  Value
 2016-01-20 15:10:04  C04     OPEN
 2016-01-20 15:09:57  M04     true
 2016-01-20 15:09:53  M02     true
 2016-01-20 15:09:53  M03     true
 2016-01-20 14:44:54  M04     true", header=T, row.names= NULL)

tmpTime <- paste(tmp[,1], tmp[,2])

group <- seq(0,55,5)

sapply(tmpTime, function(x){
  x <- minutes(x)
  for(i in 2:length(group)){
    if(x < group[i]) {return(group[i-1]); break}
    else if(x >= group[length(group)]) return(group[length(group)])
  }
})

[1] 10  5  5  5 40

这篇关于如何在R中将时间序列数据分组为5分钟的舍入间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆