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?
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
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