Make matrix symmetric
I have a matrix that should be symmetrical according to theory, but may not appear to be symmetric in my data. I would like to force this to be symmetrical using a maximum of two compared cells.
test_matrix <- matrix(c(0,1,2,1,0,1,1.5,1,0), nrow = 3)
test_matrix
#> [,1] [,2] [,3]
#>[1,] 0 1 1.5
#>[2,] 1 0 1.0
#>[3,] 2 1 0.0
It's easy enough to do it with a double loop.
for(i in 1:3){
for(j in 1:3){
test_matrix[i, j] <- max(test_matrix[i, j], test_matrix[j, i])
}
}
test_matrix
#> [,1] [,2] [,3]
#> [1,] 0 1 2
#> [2,] 1 0 1
#> [3,] 2 1 0
But my matrix is ββbigger than $ 3x3 $ and the problems with R loops are well documented. I'm also interested in keeping my code as clean as possible. Actually, I thought about putting this on code golf , but this is a real issue that I think others may be interested in.
I've seen this one as well as this one , but mine is different in that those op seem to actually have a symmetric matrix, which is just necessary for reordering, and I have a matrix that I need to change to be symmetric.
source to share
You can use pmax()
which returns the elementary maxima of a pair of vectors.
pmax(test_matrix, t(test_matrix))
# [,1] [,2] [,3]
# [1,] 0 1 2
# [2,] 1 0 1
# [3,] 2 1 0
It will work with a pair of matrices, as here, because: (1) in R, matrices are "fair" vectors with attached (dimensional) attributes; and (2) the code used to implement pmax()
is good enough to re-bind the attributes of the first argument to its return value.
source to share