Search code examples
rmatrixapply

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)


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 3x3 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