[R] Constructing a symmetric matrix with library(corpcor)

Steven Yen syen04 at gmail.com
Mon Feb 22 05:16:06 CET 2016


I like to compose a symmetric matrix in the pattern as shown below (for 3 x
3 and 4 x 4). For a symmetric matrix of order 5, the result does not seem
right. Help? It is possible to write a two-level do loop for the task, but
I suppose that is less efficient.

> library(corpcor)> r  <- 1:3; r[1] 1 2 3> rr <- vec2sm(r, diag = F); rr     [,1] [,2] [,3]
[1,]   NA    1    2
[2,]    1   NA    3
[3,]    2    3   NA> rr <- rr[upper.tri(rr)]; rr[1] 1 2 3> r  <-
vec2sm(rr, diag = F); diag(r) <- 1; r     [,1] [,2] [,3]
[1,]    1    1    2
[2,]    1    1    3
[3,]    2    3    1> r  <- 1:6; r[1] 1 2 3 4 5 6> rr <- vec2sm(r, diag
= F); rr     [,1] [,2] [,3] [,4]
[1,]   NA    1    2    3
[2,]    1   NA    4    5
[3,]    2    4   NA    6
[4,]    3    5    6   NA> rr <- rr[upper.tri(rr)]; rr[1] 1 2 4 3 5 6>
r  <- vec2sm(rr, diag = F); diag(r) <- 1; r     [,1] [,2] [,3] [,4]
[1,]    1    1    2    4
[2,]    1    1    3    5
[3,]    2    3    1    6
[4,]    4    5    6    1> r  <- 1:10; r [1]  1  2  3  4  5  6  7  8  9
10> rr <- vec2sm(r, diag = F); rr     [,1] [,2] [,3] [,4] [,5]
[1,]   NA    1    2    3    4
[2,]    1   NA    5    6    7
[3,]    2    5   NA    8    9
[4,]    3    6    8   NA   10
[5,]    4    7    9   10   NA> rr <- rr[upper.tri(rr)]; rr [1]  1  2
5  3  6  8  4  7  9 10> r  <- vec2sm(rr, diag = F); diag(r) <- 1; r
 [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    2    5    3
[2,]    1    1    6    8    4
[3,]    2    6    1    7    9
[4,]    5    8    7    1   10
[5,]    3    4    9   10    1


(Doesn't seem right).
This is what I need:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    2    4    7
[2,]    1    1    3    5    8
[3,]    2    3    1    6    9
[4,]    4    5    6    1   10
[5,]    7    8    9   10    1

>

	[[alternative HTML version deleted]]



More information about the R-help mailing list