3

我有一个动物园对象,它由一个带时间戳的(到第二个)时间序列组成。时间序列是不规则的,因为值之间的时间间隔不是规则间隔的。

我想将不规则间隔的时间序列对象转换为规则间隔的对象,其中值之间的时间间隔是恒定的——比如 15 分钟,并且是“真实世界”的时钟时间。

一些样本数据可能有助于进一步说明

# Sample data
2011-05-05 09:30:04 101.32
2011-05-05 09:30:14 100.09
2011-05-05 09:30:19 99.89
2011-05-05 09:30:35 89.66
2011-05-05 09:30:45 95.16
2011-05-05 09:31:12 100.28
2011-05-05 09:31:50 100.28
2011-05-05 09:32:10 98.28

我想在每个指定的时间段(例如 30 秒时间段)汇总它们(使用我的自定义函数),以便输出如下表所示。

关键是我想从我的第一次观察时间开始每 30 秒按时钟时间而不是 30 秒聚合一次。自然,第一个时间桶将是我在要聚合的数据中记录观察(即行)的第一个时间桶。

2011-05-05 09:30:00   101.32
2011-05-05 09:30:30   89.66
2011-05-05 09:31:00   100.28

在给出的示例中,我的自定义聚合函数仅返回“选定行”的“集合”中的第一个值以进行聚合。

4

4 回答 4

5

读入数据,然后按分钟聚合:

Lines <- "2011-05-05 09:30:04 101.32
2011-05-05 09:30:14 100.09
2011-05-05 09:30:19 99.89
2011-05-05 09:30:35 89.66
2011-05-05 09:30:45 95.16
2011-05-05 09:31:12 100.28
2011-05-05 09:31:50 100.28
2011-05-05 09:32:10 98.28"

library(zoo)
library(chron)
toChron <- function(d, t) as.chron(paste(d, t))
z <- read.zoo(text = Lines, index = 1:2, FUN = toChron)
aggregate(z, trunc(time(z), "00:01:00"), mean)

结果是:

(05/05/11 09:30:00) (05/05/11 09:31:00) (05/05/11 09:32:00) 
             97.224             100.280              98.280 
于 2012-02-06T01:53:22.843 回答
2

我希望我们可以假设这是在动物园或 xts 对象中。如果是这样,那么试试这个:

  # First get a start for a set of intervals, need to use your tz
beg<- as.POSIXct( format(index(dat[1,]), "%Y-%m-%d %H:%M", tz="EST5EDT"))
  # Then create a sequence of 30 second intervals
tseq <- beg+seq(0,4*30, by=30)
  # Then this will creat a vector than you can use for your aggregation fun
findInterval(index(dat), tseq)
  #[1] 1 1 1 2 2 3 4 5
  # To find the first row in a subset of rows from tapply, try "[" with 1
tapply(dat, findInterval(index(dat), tseq), "[", 1)
  #     1      2      3      4      5 
  #101.32  89.66 100.28 100.28  98.28 
于 2012-02-05T21:48:57.603 回答
1

我会简单地将时间截断到你的时间间隔,所以假设t是时间(as.POSIXct如果不是,则使用)

bucket = t - as.numeric(t) %% 30

然后你可以聚合过来bucket,比如aggregate(value, list(bucket), sum)

(我不使用zoo所以这是纯R)

于 2012-02-05T21:41:23.847 回答
0

你应该看看align.timexts. 它所做的事情非常接近您想要实现的目标。

my.data <- read.table(text="date,x
2011-05-05 09:30:04,101.32
2011-05-05 09:30:14,100.09
2011-05-05 09:30:19,99.89
2011-05-05 09:30:35,89.66
2011-05-05 09:30:45,95.16
2011-05-05 09:31:12,100.28
2011-05-05 09:31:50,100.28
2011-05-05 09:32:10,98.28", header=TRUE, as.is=TRUE,sep = ",")

my.data <- xts(my.data[,2],as.POSIXlt(my.data[,1],format="%Y-%m-%d %H:%M:%S"))

library(xts)
res <-align.time(my.data,30)
res[!duplicated(index(res)),]

                      [,1]
2011-05-05 09:30:30 101.32
2011-05-05 09:31:00  89.66
2011-05-05 09:31:30 100.28
2011-05-05 09:32:00 100.28
2011-05-05 09:32:30  98.28

如果它使解释更清晰,您可以将时间序列滞后 30 秒。

于 2012-02-05T21:47:16.230 回答