kgk - 5 months ago 19

R Question

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
```

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