-2

I have a matrix which contains 100 rows and 120 columns, I wonder how I can find the mean value for every 12 columns for each row. so I can have the annual mean. Thanks.

set.seed(1234)
data=rnorm(100*120)
data=matrix(data,nrow = 100,ncol = 120)
Yang Yang
  • 858
  • 3
  • 26
  • 49
  • 4
    Perhaps `sapply(split.default(as.data.frame(data), ((1:120)-1)%/%12 + 1), rowMeans)` – akrun Nov 01 '16 at 18:07
  • @akrun You are amazing. Could you explain your code a bit? Thanks. – Yang Yang Nov 01 '16 at 18:16
  • Grouped operations in R make more sense by rows, not cols. There's a dedicated function, `rowsum` for the former case. Here, it's `t(rowsum(t(data), gl(10,12)))/12` (borrowing from Gabor's answer). – Frank Nov 01 '16 at 18:22
  • `((1:120)-1)%/%12 + 1` and `gl(10, 12)` give similar results. The former gives a numeric vector while the latter gives a factor and avoids the complex formula. – G. Grothendieck Nov 01 '16 at 20:23

1 Answers1

2

For each row r, apply tapply(r, gl(10, 12), mean) to it:

t(apply(data, 1, tapply, gl(10, 12), mean))

Note that the above does not use any properties of mean so it generalizes to other aggregate functions by replacing mean with some other function.

Another possibility which also generalizes is to reshape the matrix into a 3d array and apply the mean over the indicated dimensions:

apply(array(data, c(100, 12, 10)), c(1, 3), mean)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341