Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double centering in R [closed]

Tags:

r

matrix

Do you know how to transform a matrix to a so-called double centering matrix in R? Such that sum(col) and sum(row) of the transformed matrix are all zero vector. Thanks.

like image 968
Azizah Avatar asked Mar 10 '23 06:03

Azizah


1 Answers

Double-centering a matrix M is done with the following algorithm:

  1. Generate two matrices R and C with the same size as M. R and C contain the row-wise and column-wise means respectively:
    | mean(M[1,1:3])  mean(M[1,1:3])  mean(M[1,1:3]) |
R = | mean(M[2,1:3])  mean(M[2,1:3])  mean(M[2,1:3]) |
    | mean(M[3,1:3])  mean(M[3,1:3])  mean(M[3,1:3]) | 

and

    | mean(M[1:3,1])  mean(M[1:3,2])  mean(M[1:3,3]) |
C = | mean(M[1:3,1])  mean(M[1:3,2])  mean(M[1:3,3]) |
    | mean(M[1:3,1])  mean(M[1:3,2])  mean(M[1:3,3]) |
  1. Subtract them to M and add the grand mean: M - C - R + grand_mean(M).

Here is a code performing this:

# example data
M = matrix(runif(9), nrow=3, ncol=3)

# compute the row-wise and column-wise mean matrices
R = M*0 + rowMeans(M)  # or `do.call(cbind, rep(list(rowMeans(tst)), 3))`
C = t(M*0 + colMeans(M))  # or `do.call(rbind, rep(list(colMeans(tst)), 3))`

# substract them and add the grand mean
M_double_centered = M - R - C + mean(M[])

You can check that this gives the right answer by computing rowMeans(M_double_centered) and colMeans(M_double_centered).

like image 52
Jealie Avatar answered Mar 23 '23 21:03

Jealie