Yang Yang Yang Yang - 3 months ago 30
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.

data=matrix(data,nrow = 100,ncol = 120)


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)