3

这真的是我昨天了解的问题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 指出我需要一个列感知功能(如colMeansor 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
4

1 回答 1

5

您需要在apply.weekly. 例如,使用colSums代替sumcolMeans代替mean

xtsR-forge 的最新版本给出了以下输出。当前在 CRAN 上的版本返回转置的数据。

# install.packages("xts", repos="http://r-forge.r-project.org")
> apply.weekly(zoo.daily, colSums)
                     a           b          c
2001-05-27 -1.09989120 -0.32594617  2.5178365
2001-06-03  2.31230989  0.02117512 -5.3511735
2001-06-10  0.54718941  4.34139252 -1.0462765
2001-06-13  0.06343824  2.86867857 -0.8867472
> apply.weekly(zoo.daily, colMeans)
                     a            b          c
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和的组合apply

> apply.weekly(zoo.daily, function(x) apply(x,2,mean))
                     a            b          c
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
于 2010-11-30T21:16:39.043 回答