R 找到一个更优雅的方法是使用zoo将每小时数据聚合为平均每小时数据

R 找到一个更优雅的方法是使用zoo将每小时数据聚合为平均每小时数据,r,zoo,R,Zoo,我在一年多的时间里每小时从几十台设备上记录大量的温度数据。数据存储为zoo对象。我非常想通过查看每天24小时(凌晨1点、凌晨2点、凌晨3点等)的平均值来总结这些数据。因此,对于每个设备,我可以看到所有凌晨1点、凌晨2点等的平均值。我可以用一个循环来实现这一点,但我感觉必须有一种方法在zoo中巧妙地使用aggregate.zoo来实现这一点。有什么帮助吗 require(zoo) # random hourly data over 30 days for five series x <- m

我在一年多的时间里每小时从几十台设备上记录大量的温度数据。数据存储为zoo对象。我非常想通过查看每天24小时(凌晨1点、凌晨2点、凌晨3点等)的平均值来总结这些数据。因此,对于每个设备,我可以看到所有凌晨1点、凌晨2点等的平均值。我可以用一个循环来实现这一点,但我感觉必须有一种方法在zoo中巧妙地使用aggregate.zoo来实现这一点。有什么帮助吗

require(zoo)
# random hourly data over 30 days for five series
x <- matrix(rnorm(24 * 30 * 5),ncol=5)
# Assign hourly data with a real time and date
x.DateTime <- as.POSIXct("2014-01-01 0100",format = "%Y-%m-%d %H") + 
  seq(0,24 * 30 * 60 * 60, by=3600)
# make a zoo object
x.zoo <- zoo(x, x.DateTime)
#plot(x.zoo)

# what I want:
# the average value for each series at 1am, 2am, 3am, etc. so that
# the dimensions of the output are 24 (hours) by 5 (series)
# If I were just working on x I might do something like:
res <- matrix(NA,ncol=5,nrow=24)
for(i in 1:nrow(res)){
  res[i,] <- apply(x[seq(i,nrow(x),by=24),],2,mean)
}
res
# how can I avoid the loop and write an aggregate statement in zoo that 
# will get me what I want?
require(动物园)
#五个系列30天内的随机每小时数据

x计算每个时间点的小时数,然后通过以下公式进行汇总:

hr <- as.numeric(format(time(x.zoo), "%H"))
ag <- aggregate(x.zoo, hr, mean)
dim(ag)
## [1] 24  5

计算每个时间点的小时数,然后根据该时间点进行汇总:

hr <- as.numeric(format(time(x.zoo), "%H"))
ag <- aggregate(x.zoo, hr, mean)
dim(ag)
## [1] 24  5

这与另一个答案非常相似,但利用了
by=…
参数到
aggregate.zoo(…)
可以是一个应用于
time(x.zoo)
的函数:


as.hour这与另一个答案非常相似,但它利用了
by=…
参数到
aggregate.zoo(…)
可以是一个应用于
time(x.zoo)
的函数:


as.hour啊。因此,为每一个只有小时的点创建一个索引。非常明智。谢谢。因此,为每一个只有小时的点创建一个索引。非常明智。谢谢。将函数编写为.hour()可以使其更普遍地适用。这将派上用场,因为我有不同的数据集来应用它。非常感谢。许多软件包还定义了一些函数,用于记录日期/时间并生成小时。例如,chron包中的
hours
。将函数编写为.hour()可以更普遍地应用。这将派上用场,因为我有不同的数据集来应用它。非常感谢。许多软件包还定义了一些函数,用于记录日期/时间并生成小时。例如,chron包中的
hours
as.hour <- function(t) as.numeric(format(t,"%H"))
result  <- aggregate(x.zoo,as.hour,mean)
identical(result,ag)    # ag from G. Grothendieck answer
# [1] TRUE