[R] Flattening and unflattening symmetric matrices

David Winsemius dwinsemius at comcast.net
Sat May 1 00:47:06 CEST 2010


On Apr 30, 2010, at 5:26 PM, Nicholas Andrews wrote:

> Here's an easy question: I'd like to convert a symmetric matrix to a
> vector composed of the upper.tri() part of it plus the diagonal, and
> convert it back again.  What's the best way to achieve this?  I'm
> wondering if there are some built in functions to do this easily.  I
> can encode fine:
>
> v <- c(diag(A),A[upper.tri(A)])
>
> but I don't see an easy way to recover A from v without loops.  Any  
> tips?

  mtx <- matrix(1:9, 3,3)
  v  <- c(diag(mtx), mtx[upper.tri(mtx)])
  mtx2 <- matrix( , 3,3)               #init

2 part indexing appraoch:
  mtx2[row(mtx2)==col(mtx2)] <- v[1:3] #could use 1:length(diag(mtx))
  mtx2[upper.tri(mtx2)] <- v[4:6]      #logical indexing with "[<-"

 > mtx2
      [,1] [,2] [,3]
[1,]    1    4    7
[2,]   NA    5    8
[3,]   NA   NA    9

Would it be any easier to use upper.tri( , diag=TRUE)? It wouldn't put  
all your diag elements together, but it would be reversible.

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list