Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a symmetric matrix in R

Tags:

r

symmetric

People also ask

How do you find a 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.

How do you make an 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.


s<-matrix(1:25,5)
s[lower.tri(s)] = t(s)[lower.tri(s)]

You can force the matrix to be symmetric using forceSymmetric function in Matrix package in R:

library(Matrix)
x<-Matrix(rnorm(9), 3)
> x
3 x 3 Matrix of class "dgeMatrix"
           [,1]       [,2]       [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,]  0.7076883 -1.0411563  0.4324291
[3,] -0.4108909 -0.3292247 -0.3076071

A <- forceSymmetric(x)
> A
3 x 3 Matrix of class "dsyMatrix"
           [,1]       [,2]       [,3]
[1,] -1.3484514 -0.4460452 -0.2828216
[2,] -0.4460452 -1.0411563  0.4324291
[3,] -0.2828216  0.4324291 -0.3076071

Is the workaround really necessary if the values only differ by that much?

Someone pointed out that my previous answer was wrong. I like some of the other ones better, but since I can't delete this one (accepted by a user who left), here's yet another solution using the micEcon package:

symMatrix(s[upper.tri(s, TRUE)], nrow=nrow(s), byrow=TRUE)

 s<-matrix(1:25,5)
 pmean <- function(x,y) (x+y)/2
 s[] <- pmean(s, matrix(s, nrow(s), byrow=TRUE))
 s
#-------
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    4    7   10   13
[2,]    4    7   10   13   16
[3,]    7   10   13   16   19
[4,]   10   13   16   19   22
[5,]   13   16   19   22   25