这真的是我昨天了解的问题apply.weekly
的延伸。这很好用,但我想在宽zoo
对象上执行此操作。如果我apply.weekly
在广泛使用zoo
它对列求和,然后执行每周聚合:
> library(xts)
> set.seed(2001)
> zoo.daily <- zoo(data.frame(a=rnorm(20), b=rnorm(20), c=rnorm(20)), order.by=as.Date("2001-05-25") + 0:19)
> apply.weekly(zoo.daily, sum)
2001-05-27 2001-06-03 2001-06-10 2001-06-13
1.091999 -3.017688 3.842305 2.045370
> apply.weekly(zoo.daily[, 1] + zoo.daily[, 2] + zoo.daily[, 3], sum)
2001-05-27 2001-06-03 2001-06-10 2001-06-13
1.091999 -3.017688 3.842305 2.045370
我尝试了apply
操作符系列,但它们似乎去掉了zoo
日期索引。我可以for
循环执行,但这确实很耗时(比周期性aggregate
函数慢四倍多)。as.yearmon
这是for
循环:
week.ends <- index(zoo.daily[endpoints(zoo.daily, "weeks")[-1], ])
num.weeks <- nweeks(zoo.daily)
num.stocks <- ncol(zoo.daily)
zoo.weeks <- zoo(matrix(NA, num.weeks, num.stocks), order.by=week.ends)
for (i in seq(num.stocks)) {
zoo.weeks[, i] <- apply.weekly(zoo.daily[, i], mean)
}
哪个有效(即,保持每个向量分开):
2001-05-27 -0.36663040 -0.108648725 0.8392788
2001-06-03 0.33032998 0.003025018 -0.7644534
2001-06-10 0.07816992 0.620198931 -0.1494681
2001-06-13 0.02114608 0.956226189 -0.2955824
有没有办法快速对所有列进行操作apply.weekly
?谢谢!
更新:Joshua Ulrich 指出我需要一个列感知功能(如colMeans
or colSums
)。当我这样做时,我得到了正确的答案,但作为一个转置矩阵。我应该重新分类并继续前进吗?还是我有一个选项/设置错误?
> apply.weekly(zoo.daily, colSums)
[,1] [,2] [,3] [,4]
a -1.0998912 2.31230989 0.5471894 0.06343824
b -0.3259462 0.02117512 4.3413925 2.86867857
c 2.5178365 -5.35117351 -1.0462765 -0.88674717