[R] how to convert the lower triangle of a matrix to a symmetric matrix

Charles C. Berry cberry at tajo.ucsd.edu
Fri Apr 20 05:53:38 CEST 2007


On Thu, 19 Apr 2007, Ranjan Maitra wrote:

> Hi,
>
> I have a vector of p*(p+1)/2 elements, essentially the lower triangle of 
> a symmetric matrix. I was wondering if there is an easy way to make it 
> fill a symmetric matrix. I have to do it several times, hence some 
> efficient approach would be very useful.

It depends on what the ordering of elements in your vector is.

Many programs will order those elements (1,1), (2,1), (2,2), (3,1) , ...

In which case this shows how:


> k.given.i.j <- function(x , y ) ifelse( y<x, x*(x-1)/2 + y, y*(y-1)/2 + x )
> k.mat <- function(p) outer( 1:p, 1:p, k.given.i.j )
> k.mat( 3 )
      [,1] [,2] [,3]
[1,]    1    2    4
[2,]    2    3    5
[3,]    4    5    6
> matrix( rnorm( choose(4,2) )[ k.mat( 3 ) ] , nr = 3 )
            [,1]        [,2]        [,3]
[1,] -1.2165313  0.28262740  0.62448849
[2,]  0.2826274 -1.19842868  0.05676263
[3,]  0.6244885  0.05676263 -1.80957190
>

For efficiency, you might save and reuse the result of k.mat().

If the elements are ordered (1,1), (2,1), (3,1), ..., you will need to 
write your own version of k.given.i.j()



>
> Many thanks and best wishes,
> Ranjan
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>

Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0901



More information about the R-help mailing list