2
votes

I have a daily time series data and wish to construct a daily moving average and create a quarterly data frame. As an example the first data set (of the example data) should include daily data for the months January, February and March, while the second series should be February, March and April. Similarly, the last data set should be that of October, November and December. I wish to do this for the variables “tmpd, pm10median and so2median” in the sample data. How can I achieve this?

library(gamair) 
data(chicago) 
chicago$date<-seq(from=as.Date("1987-01-01"), to=as.Date("2000-12-31"),length=5114)
data<- chicago[,c("date","tmpd", "pm10median", "so2median" )]
1
Well, to be honest nothing useful to solve the issue. I have tried to create moving average, with this: library(zoo) data$rollmean <- rollmean(data$tmpd, 2, fill = NA). But that is not my main concern.Meso

1 Answers

1
votes

Using xts package , you can do something like this

library(xts)
dat.ts <- xts(x=data[,-1],                   ## create an xts object 
              order.by=as.Date(data[,1]))    ## coerce the index to date
dat.quart <- apply.quarterly(dat.ts,mean)    ## apply for each quarter

To show some rows:

 rbind(head(dat.quart),tail(dat.quart))
               tmpd pm10median  so2median
1987-03-31 33.60556         NA         NA
1987-06-30 62.19231         NA -0.3283393
1987-09-30 71.31522         NA -1.9137842
1987-12-31 41.09783         NA         NA
1988-03-31 27.06593         NA         NA
1988-06-30 60.48352         NA         NA
1999-09-30 71.01087   2.697414 -0.4532943
1999-12-31 42.86957   1.565251 -0.4035715
2000-03-31 34.74725  -4.704813  0.2392453
2000-06-30 59.07692         NA -0.5426823
2000-09-30 69.67391         NA -1.9221470
2000-12-31 36.59783         NA -0.2387025

UPDATE

It looks that the OP wants to split the Moving average series by quarter.

dat.ts <- xts(x=data[,-1],                   ## create an xts object 
              order.by=as.Date(data[,1]))    ## coerce the index to date
dat.m <- rollmean(dat.ts,k=2)                ## compute the MA
ep <- endpoints(dat.m, "quarters")           ## create an index
## this split the seriers by quarter
xx <- sapply(1:(length(ep) - 1), function(y) { 
  dat.m[(ep[y] + 1):ep[y + 1]]
})