[R] Flattening and unflattening symmetric matrices

Peter Ehlers ehlers at ucalgary.ca
Sat May 1 01:14:34 CEST 2010


On 2010-04-30 15:26, 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?

To (re)create a symmetric matrix, use A + t(A):
If vd is diag(A) part of v and vu is the rest of v, and
let's take A to be 4-by-4, then

  A <- matrix(0, 4, 4)
  A[upper.tri(A)] <- vu
  A <- A + t(A)
  diag(A) <- vd
  A

  -Peter Ehlers

>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

-- 
Peter Ehlers
University of Calgary



More information about the R-help mailing list