[R] Up- or downsampling time series in R

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Thu Oct 26 19:07:37 CEST 2006


On Thu, 26 Oct 2006, Brandt, T. (Tobias) wrote:

> I have data that is sampled (in time) with a certain frequency and I would
> like to express this time series as a time series of a higher (or lower)
> frequency with the newly added time points being filled in with NA, 0, or
> perhaps interpolated. My data might be regularly or irregularly spaced. For
> example, I might have quarterly data that I would like to handle as a
> monthly time series with NAs filled in for the missing months.

Both can be done easily with zoo, examples for both are given in the
package vignettes and the man pages of the package.

1. extend to a finer grid (upsampling)
## generate some time series
z <- zoo(sample(1:3, 20, replace=TRUE),
         as.yearmon(seq(2000, by=0.5, length=20)))
## generate emtpy series on finer grid
z2 <- zoo(,seq(start(z), end(z), by = 1/12))
## merge (returns univariate series, by default filled with NAs)
merge(z, z2)

2. aggregate to a coarser grid (downsampling)
## transform to annual data
as.annual <- function(x) floor(as.numeric(x))
## average within years
aggregate(z, as.annual, mean)
## first observation within year
aggregate(z, as.annual, head, 1)

hth,
Z



More information about the R-help mailing list