Creating a symmetric matrix in R

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)

Tags:

R

Symmetric