[R] aggregating a daily zoo object to a weekly zoo object
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Aug 2 01:40:25 CEST 2010
On Sun, Aug 1, 2010 at 6:06 PM, Erin Hodgess <erinm.hodgess at gmail.com> wrote:
> Dear R People:
>
> I'm trying to convert a daily zoo object to a weekly zoo object:
>
>
> xdate <- seq(as.Date("2002-01-01"),as.Date("2010-07-10"),by="day")
> library(zoo)
> length(xdate)
> xt <- zoo(rnorm(3113),order=xdate)
> xdat2 <- seq(index(xt)[1],index(xt)[3113],by="week")
> xt.w <- aggregate(xt,by=xdat2,mean)
> Error: length(time(x)) == length(by[[1]]) is not TRUE
> aggregate(xt,by="week",mean)
> Error: length(time(x)) == length(by[[1]]) is not TRUE
>
by must be the same length as the series. It then aggregates over all
values of the series with the same by value and gives that aggregated
value the common by value as its time. So you need to create a by that
maps all dates in a week to the first date in the week (or the last
date in the week), e.g.
library(zoo)
z <- zooreg(1:30, as.Date("2002-02-01"))
aggregate(z, as.Date(7 * floor(as.numeric(time(z)) / 7)), mean)
Its particularly easy if you use chron since you can use trunc.times:
library(zoo)
library(chron)
zc <- zooreg(1:30, as.chron("2002-02-01"))
aggregate(zc, trunc(time(zc), 7), mean)
or this which starts out with Date, converts to chron to use
trunc.times and then converts back:
aggregate(z, as.Date(trunc(as.chron(time(z)), 7)), mean)
See ?trunc.times in chron.
More information about the R-help
mailing list