[R] means by group

Petr Savicky savicky at cs.cas.cz
Fri May 4 08:56:04 CEST 2012


On Thu, May 03, 2012 at 09:07:39PM -0400, li li wrote:
> Hi all,
>    I have a 100 by 100 matrix and I divided this matrix into 100 groups,
> each is a
>   10 by 10 submatrix. I want find out the means of each group.
>    I know we can use apply function for mean by margins. Is there a
> function in R for
> means by groups also? Thanks.

Hi.

Try the following with k = 10, n = 100.

  k <- 3
  n <- 6
  A <- matrix(1:(n^2), nrow=n, ncol=n)
  B <- matrix(nrow=n, ncol=n)
  B[, ] <- paste((row(B)-1) %/% k + 1, (col(B)-1) %/% k + 1, sep=",")
  B

       [,1]  [,2]  [,3]  [,4]  [,5]  [,6] 
  [1,] "1,1" "1,1" "1,1" "1,2" "1,2" "1,2"
  [2,] "1,1" "1,1" "1,1" "1,2" "1,2" "1,2"
  [3,] "1,1" "1,1" "1,1" "1,2" "1,2" "1,2"
  [4,] "2,1" "2,1" "2,1" "2,2" "2,2" "2,2"
  [5,] "2,1" "2,1" "2,1" "2,2" "2,2" "2,2"
  [6,] "2,1" "2,1" "2,1" "2,2" "2,2" "2,2"

  tapply(c(A), c(B), FUN=mean)

  1,1 1,2 2,1 2,2 
    8  26  11  29 

For verification, try

  mean(A[1:k, 1:k])           # [1] 8
  mean(A[1:k, 1:k + k])       # [1] 26
  mean(A[1:k + k, 1:k])       # [1] 11
  mean(A[1:k + k, 1:k + k])   # [1] 29

Hope this helps.

Petr Savicky.



More information about the R-help mailing list