I have a lower triangular of a matrix that I'm trying to convert to a dissim matrix and thus it needs to be symmetric.
print(rdf)
X0 X1 X2 X3 X4
0 0.0000000 NA NA NA NA
1 0.5340909 0.0000000 NA NA NA
2 0.5340909 0.0000000 0.0000000 NA NA
3 0.3200000 0.5227273 0.5227273 0.0000000 NA
4 0.6263736 0.4945055 0.4945055 0.5384615 0
library(gdata)
upperTriangle(rdf) <- lowerTriangle(rdf)
isSymmetric(rdf)
X0 X1 X2 X3 X4
0 0.0000000 0.5340909 0.5340909 0.6263736 0.4945055
1 0.5340909 0.0000000 0.3200000 0.0000000 0.5227273
2 0.5340909 0.0000000 0.0000000 0.5227273 0.4945055
3 0.3200000 0.5227273 0.5227273 0.0000000 0.5384615
4 0.6263736 0.4945055 0.4945055 0.5384615 0.0000000
[1] FALSE
What is going on? Note, I don't need to use gdata
To convert given matrix into the lower triangular matrix, loop through the matrix and set the values of the element to zero where column number is greater than row number.
tri() function in R Language is used to return a matrix of logical values with upper triangle as TRUE.
To create an upper triangular matrix using vector elements, we can first create the matrix with appropriate number of columns and rows then take the transpose of that matrix. After that we will assign the lower triangular matrix elements to 0.
isSymmetric() function in R Language is used to check if a matrix is a symmetric matrix. A Symmetric matrix is one whose transpose is equal to the matrix itself.
You need to make sure that the elements you're copying are ordered correctly:
m <- matrix(NA,4,4)
m[lower.tri(m,diag=TRUE)] <- 1:10
[,1] [,2] [,3] [,4]
[1,] 1 NA NA NA
[2,] 2 5 NA NA
[3,] 3 6 8 NA
[4,] 4 7 9 10
makeSymm <- function(m) {
m[upper.tri(m)] <- t(m)[upper.tri(m)]
return(m)
}
makeSymm(m)
Or you can use the built-in
Matrix::forceSymmetric(m,uplo="L")
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