Double centering in R

Do you know how to convert matrix to so called double centering matrix in R? So the sum (col) and the sum (row) of the transformed matrix are all zero vectors. Thank.

+3


source to share


1 answer


Double centering of the matrix M is performed with the following algorithm:

1) generate two matrices of the same size as the original matrix, containing equally and columns. Let's call these two matrices R and C:

    | 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]) | 

      



2) Subtract them M and add tremendous value: M - C - R + grand_mean(M)

.

Here's the code to accomplish 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 correct answer by calculating rowMeans(M_double_centered)

and colMeans(M_double_centered)

.

+3


source







All Articles