[R] Summing over intervals

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jul 15 22:51:47 CEST 2010


On Thu, Jul 15, 2010 at 4:21 PM, Dennis Murphy <djmuser at gmail.com> wrote:
> Hi:
>
> Tal was on the right track, but the function in package zoo that applies
> here is rollapply():
>
> library(zoo)
> m<-matrix(seq(1,80),ncol=20, nrow=4)
> t(apply(m, 1, function(x) rollapply(zoo(x), width = 5, FUN = mean, by = 5)))
>     [,1] [,2] [,3] [,4]
> [1,]    9   29   49   69
> [2,]   10   30   50   70
> [3,]   11   31   51   71
> [4,]   12   32   52   72
>
> The width argument determines the number of values per subgroup to process,
> and by determines the spacing between 'windows' of values. Since the
> objective here was to summarize nonoverlapping blocks of size 5, both width
> and by have to be specified with the same value.
>

Just to build on Dennis' solution rollapply will act column by column
so we can reduce it slightly to:

   out <- t(rollapply(zoo(t(m)), 5, by = 5, mean))
   dimnames(out) <- NULL # optional



More information about the R-help mailing list