Thank you very much, Gabor! Dimitri On Tue, Jul 13, 2010 at 12:25 PM, Gabor Grothendieck <ggrothendi...@gmail.com> wrote: > On Tue, Jul 13, 2010 at 11:19 AM, Dimitri Liakhovitski > <dimitri.liakhovit...@gmail.com> wrote: >> Actually, >> I realized that my task was a bit more complicated as I have different >> (let's call them) Markets and the dates repeat themselves across >> markets. And the original code from Gabor gives an error - because >> dates repeate themselves and apparently zoo cannot handle it. So, I >> had to do program a way around it (below). It works. >> However, I am wondering if there is a shorter/more elegant way of doing it? >> Thank you! >> Dimitri >> >> ### My original data frame is a bit more complicated - dates repeat >> themselves for 2 markets: >> monthly<-data.frame(month=c(20100301,20100401,20100501,20100301,20100401,20100501),monthly.value=c(100,200,300,10,20,30),market=c("Market >> A","Market A", "Market A","Market B","Market B", "Market B")) >> monthly$month<-as.character(monthly$month) >> monthly$month<-as.Date(monthly$month,"%Y%m%d") >> (monthly) >> > > Assuming the dates for each market are the same we split them into a > zoo object with one market per column and following the same approach > as last time we use by in place of ave. The lines marked ## are same > as last time. > Be sure you are using zoo 1.6-4 from CRAN since it makes use of the > na.locf features added in that version. > >> z <- read.zoo(monthly, split = "market") >> all.dates <- seq(start(z), as.Date(as.yearmon(end(z)), frac = 1), by = >> "day") ## >> mondays <- all.dates[weekdays(all.dates) == "Monday"] ## >> weeks <- na.locf(z, xout = mondays) ## >> do.call(rbind, by(weeks, as.yearmon(mondays), > + function(x) zoo(x/nrow(x), rownames(x)))) > Market.A Market.B > 2010-03-01 20 2 > 2010-03-08 20 2 > 2010-03-15 20 2 > 2010-03-22 20 2 > 2010-03-29 20 2 > 2010-04-05 50 5 > 2010-04-12 50 5 > 2010-04-19 50 5 > 2010-04-26 50 5 > 2010-05-03 60 6 > 2010-05-10 60 6 > 2010-05-17 60 6 > 2010-05-24 60 6 > 2010-05-31 60 6 >
-- Dimitri Liakhovitski Ninah Consulting www.ninah.com ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.