[R] converting monthly to weekly without changing the original values

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Wed Aug 4 18:42:33 CEST 2010


Sorry, I found the solution:

library(zoo)
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, na.rm = FALSE, maxgap=0)
do.call(rbind, by(weeks, as.yearmon(mondays), function(x) zoo(x, rownames(x))))

Dimitri



On Wed, Aug 4, 2010 at 12:36 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
> Hello!
> I have a code for converting monthly values into weekly values:
>
> monthly<-data.frame(month=c(20100301,20100401,20100501,20100601,20100301,20100401,20100501,20100601),monthly.value=c(100,NA,200,300,10,NA,20,30),market=c("Market
> A","Market A","Market A","Market A","Market B","Market B","Market
> B","Market B"))
> monthly$month<-as.character(monthly$month)
> monthly$month<-as.Date(monthly$month,"%Y%m%d")
> (monthly)
>
> library(zoo)
> 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, na.rm = FALSE) ##
> do.call(rbind, by(weeks, as.yearmon(mondays), function(x)
> zoo(x/nrow(x), rownames(x))))
>
>
> I have 2 questions:
> 1. How can I make the code above leave NAs that were present in
> "monthly" as NAs in all weeks of the corresponding month - rather than
> impute them as it currently does?
> 2. In addition to 1, how can I ask zoo to actually keep the original
> (monthly) values in each week of that month - rather than divide the
> monthly value by the number of weeks?
>
>
> Thanks a lot!
>
>
>
> --
> Dimitri Liakhovitski
> Ninah Consulting
> www.ninah.com
>



-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list