[R] generating random covariance matrices (with a uniform distribution of correlations)

Ned Dochtermann ned.dochtermann at gmail.com
Fri Jun 3 22:54:33 CEST 2011


Petr,
This is the code I used for your suggestion:

	k<-6;kk<-(k*(k-1))/2
	x<-matrix(0,5000,kk)
	for(i in 1:5000){
	A.1<-matrix(0,k,k)
	rs<-runif(kk,min=-1,max=1)
	A.1[lower.tri(A.1)]<-rs
	A.1[upper.tri(A.1)]<-t(A.1)[upper.tri(A.1)]
	cors.i<-diag(k)
	t<-.001-min(Re(eigen(A.1)$values))
	new.cor<-cov2cor(A.1+(t*cors.i))
	x[i,]<-new.cor[lower.tri(new.cor)]}
	hist(c(x)); max(c(x)); median(c(x))

This, unfortunately, does not maintain the desired distribution of
correlations.
I did, however, learn some neat coding tricks (that were new for me) along
the way.

Ned
--
On Thu, Jun 02, 2011 at 04:42:59PM -0700, Ned Dochtermann wrote:
> List members,
> 
> Via searches I've seen similar discussion of this topic but have not seen
> resolution of the particular issue I am experiencing. If my search on this
> topic failed, I apologize for the redundancy. I am attempting to generate
> random covariance matrices but would like the corresponding correlations
to
> be uniformly distributed between -1 and 1. 
> 
...
> 
> Any recommendations on how to generate the desired covariance matrices
would
> be appreciated.

Hello.

Let me suggest the following procedure.

1. Generate a symmetric matrix A with the desired distribution of the
   non-diagonal elements and with zeros on the diagonal.
2. Compute the smallest eigenvalue lambda_1 of A.
3. Replace A by A + t I, where I is the identity matrix and t is a
   number such that t + lambda_1 > 0.

The resulting matrix will have the same non-diagonal elements as A,
but will be positive definite.

Petr Savicky.



More information about the R-help mailing list