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.
Double-centering a matrix M is done with the following algorithm:
| 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]) |
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With