-1

I have a data frame and I want to take average of every 60 records for all the columns, and return a new data frame.

For example, I want to take average of every column from row 1 to row 60, then row 61-row 120, then 121-180, likewise...and go thru the whole data frame. Then have all these means summarized under one table as new data frame.

Any one can help me? Thanks so much!

  • 2
    Hi there! Please make your post reproducible by having a look at [**How to make a great reproducible example**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for us to help you. Thank you. – Arun Apr 10 '13 at 18:28
  • Usually, this isn't a very nice programming practice. It's better to specify the variables and values that define these groups, not just rows 1-60, 61-120,... – Ferdinand.kraft Apr 11 '13 at 01:46

2 Answers2

2

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
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
0

Obviously not tested on your data but was tested on the first example in help(aggregate)

dflen <- nrow(dfrm)
aggregate(dfrm, list(rep(1:(dflen/60 +1), each=60, length=dflen) ), mean)
IRTFM
  • 258,963
  • 21
  • 364
  • 487