Yang Yang Yang Yang - 1 month ago 11
R Question

How to average every 12 columns for each row in r

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)

Answer

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 take the mean over the indicated dimensions:

apply(array(data, c(100, 12, 10)), c(1, 3), mean)