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(mat4)
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.
CodePudding user response:
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
CodePudding user response:
The problem is how the row names are generated when you converted it to a matrix. You fix this by using this:
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))
mat2 = as.matrix(mat1)
rownames(mat2) <- colnames(mat2)
isSymmetric(mat2)
#> [1] TRUE
Created on 2022-07-06 by the reprex package (v2.0.1)
Another option is setting check.attributes=FALSE
like this:
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))
mat2 = as.matrix(mat1)
isSymmetric(mat2, check.attributes = FALSE)
#> [1] TRUE
Created on 2022-07-06 by the reprex package (v2.0.1)