vendredi 31 janvier 2020

R: how to make a random correlation matrix semi definite positive

I am trying to make a random matrix correlation over 183 variables to calculate a Cholesky decomposition and correlate 183 random normals. For the creation of the correlation matrix the following reproducible code is the one I am using:

First I set the seed

set.seed(2)

Then I generate random numbers between 0.6 and 0.8

corr <- matrix(runif(183*183, min = 0.6, max = 0.8), 183, 183)

The next step is turning the diagonal into ones

for (i in 1:183) {
  for (j in 1:183) {
    if (i == j) {
    corr[i,j] <- 1
    }
  }
}

Last step is making it symmetric

for (i in 1:183) {
  for (j in 1:183) {
    if (i < j) {
    corr[i,j] <- corr[j,i]
    }
  }
}

The problem I run into arise when I try to make the cholesky decomposition

cholesky <- chol(corr)

I get the following error:

Error in chol.default(corr) : the leading minor of order 14 is not positive definite

How could I make my correlation matrix semi definite positive?




Aucun commentaire:

Enregistrer un commentaire