I was doing something convoluted with lapply
, and colMeans
before I realised that it would be much easier with rollapply
from package:zoo
. For the sake of completeness I show how the two approaches yeild identical results on some dummy data, which is 5 columns wide by 120 rows long:
data <- data.frame(matrix(runif(600),nrow=120))
nrows <- 60
t(sapply( rev(1:floor(nrow(data)/nrows)) , function(x){ colMeans(data[c(rev(seq.int( nrow(data)/x))[1:60]),]) } ))
X1 X2 X3 X4 X5
# [1,] 0.4706680 0.4780024 0.4749281 0.4910620 0.4815172
# [2,] 0.5236926 0.4385900 0.4979433 0.4787086 0.5616210
Or more simply with rollapply()
require(zoo)
rollapply(data, 60, FUN = mean , by = 60 )
X1 X2 X3 X4 X5
# [1,] 0.4706680 0.4780024 0.4749281 0.4910620 0.4815172
# [2,] 0.5236926 0.4385900 0.4979433 0.4787086 0.5616210