Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate square symmetric matrix in R

I have a matrix in R as follows:

dat <- matrix(c(2,3,5,7,8,4), ncol = 6)
colnames(dat) <- c("A(1,1)", "A(1,2)", "A(1,3)", "A(2,2)", "A(2,3)", "A(3,3)")

How can I create a square symmetric matrix based on an apply function that has the following form:

A(1,1) A(1,2) A(1,3)
A(2,1) A(2,2) A(2,3)
A(3,1) A(3,2) A(3,3)

Note that A(1,2)=A(2,1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This isn’t based on apply but it shows how you can use lower.tri and upper.tri to create a symmetric matrix given a vector of elements. It shows the 3×3 case, but will easily generalize to larger n:

dat <- matrix(rep(0,9),nrow = 3)
dat[lower.tri(dat,diag = TRUE)] <- c(2,3,5,7,8,4)
dat[upper.tri(dat)] <- t(dat)[upper.tri(dat)]
print(dat)

Result:

     [,1] [,2] [,3]
[1,]    2    3    5
[2,]    3    7    8
[3,]    5    8    4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading