Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: make symmetric matrix from lower diagonal [duplicate]

Tags:

r

matrix

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

like image 969
jwillis0720 Avatar asked Oct 08 '15 21:10

jwillis0720


People also ask

How do you turn a matrix into a lower triangle?

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.

What does upper tri do in R?

tri() function in R Language is used to return a matrix of logical values with upper triangle as TRUE.

How do you make a upper triangular matrix in R?

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.

Is symmetric matrix in R?

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.


1 Answers

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")
like image 75
Ben Bolker Avatar answered Oct 16 '22 09:10

Ben Bolker