This is really an extension of my question yesterday where I learned about apply.weekly
. This works great, but I want to do this over wide zoo
objects. If I use apply.weekly
on a wide zoo
it sums the columns, then performs the weekly aggregation:
> 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
I tried the apply
family of operators, but those seem to strip out the zoo
date index. I can do it in a for
loop, but it's really time-consuming (much, much more than a factor of four slower than the aggregate
function on as.yearmon
periodicity). Here's the for
loop:
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)
}
Which works (i.e., keeps each vector separate):
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
Is there a way to quickly operate on all columns with apply.weekly
? Thanks!
UPDATE: Joshua Ulrich points out that I need a column aware function (like colMeans
or colSums
). When I do this, I get the correct answers, but as a transposed matrix. Should I just reclass and move on? Or do I have an option/setting wrong?
> 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