Erin Hodgess
2010-Aug-01 22:06 UTC
[R] aggregating a daily zoo object to a weekly zoo object
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 I'm not sure what is going wrong. Any help would be much appreciated. Thanks, Erin -- Erin Hodgess Associate Professor Department of Computer and Mathematical Sciences University of Houston - Downtown mailto: erinm.hodgess at gmail.com
Gabor Grothendieck
2010-Aug-01 23:40 UTC
[R] aggregating a daily zoo object to a weekly zoo object
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.