kgk kgk - 3 months ago 9
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

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,])))
dim(B) 
#[1]  20 100

data

A <- matrix(1:40000, nrow = 400, ncol= 100)
Comments