kgk kgk - 1 year ago 83
R Question

Get average of a number of rows in all of the columns in R

I have a matrix A[400x100] . How could I get the average of each 20 rows in each columns. Finally, I put all the values into matrix B[20,100]. For example :

B[1,1] = mean(A[1:20])
B[2,1] = mean(A[21:40]) .....

Answer Source

We can do

i1 <- as.numeric(gl(nrow(A), 20, nrow(A)))
B <- t(sapply(split(seq_len(nrow(A)), i1), function(i) colMeans(A[i,])))
#[1]  20 100


A <- matrix(1:40000, nrow = 400, ncol= 100)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download