On 2012-10-26 08:58, David Winsemius wrote:

>

> On Oct 26, 2012, at 6:52 AM, F_Smithers wrote:

>

>> I'm looking to create a correlation matrix, but I have already obtained the

>> correlations, which are stored in a vector. (Basically, I'm running a

>> simulation which requires a correlation matrix, but I am simulating the

>> various correlations.)

>>

>> My aim is to create a function that can take the vector, and fit the values

>> into their respective locations in a correlation matrix. (The correlations

>> are ordered as if working along the upper triangle of the correlation matrix

>> row-wise.)

>>

>> The initial step in the function was to create a diagonal matrix of length

>> n, (n being the number of factors) and then add the correlations at each

>> level using a for command.

>

>> mat<- matrix(1:16, 4,4)

>> mat[ upper.tri(mat) ]

> [1] 5 9 10 13 14 15

>> newmat <- matrix(NA, 4,4)

>> newmat[ upper.tri(newmat) ] <- mat[ upper.tri(mat) ]

>> newmat

> [,1] [,2] [,3] [,4]

> [1,] NA 5 9 13

> [2,] NA NA 10 14

> [3,] NA NA NA 15

> [4,] NA NA NA NA

>> newmat[ lower.tri(newmat) ] <- t(newmat[upper.tri(newmat)])

>> newmat

> [,1] [,2] [,3] [,4]

> [1,] NA 5 9 13

> [2,] 5 NA 10 14

> [3,] 9 13 NA 15

> [4,] 10 14 15 NA

>> diag(newmat) <- 1

>> newmat

> [,1] [,2] [,3] [,4]

> [1,] 1 5 9 13

> [2,] 5 1 10 14

> [3,] 9 13 1 15

> [4,] 10 14 15 1

>

This doesn't quite work; the resulting matrix is not symmetrical.

The culprit is the t(newmat[....]) line. I find it easiest to

start with a matrix of zeros, fill in the upper.tri part as you

have done, then just add newmat and t(newmat), then fix the diagonal.

Peter Ehlers

______________________________________________

[hidden email] mailing list

https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide

http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.