I want to test the symmetry of matrices in R 4.1.1. I have a dataframe and then I convert it to a matrix. The data type with class()
function returns now both a "matrix"
and an "array"
. The matrix is symmetric, but the function isSymmetric()
returns FALSE
.
This is what I do:
## Sample dataframe
mat1=data.frame(one=c(64,1,2,0),two=c(1,0,0,0),three=c(2,0,6,45),four=c(0,0,45,140))
## now we convert it to matrix
mat2 = as.matrix(mat1)
class(mat2)
## Note how this will return FALSE, even when its symmetric
isSymmetric(mat2)
## Now I turn the matrix into a vector and convert it again.
mat3 = matrix(as.numeric(mat2),
nrow = dim(mat2)[1])
class(mat3)
## Now this works:
isSymmetric(mat3)
My question is: Is there a more straightforward way, other than melting the matrix and building it again, to check for symmetry of a matrix? I need to read many large matrices and this is a quite convoluted way to deal with this.
According to documentation:
Note that a matrix m is only symmetric if its rownames and colnames are identical. Consider using unname(m).
isSymmetric(unname(mat2))
[1] TRUE