I would like to simulate data with different correlation matrices, with this method:
M = matrix(c(1.0, 0.6, 0.6, 0.6,
0.6, 1.0, -0.2, 0.0,
0.6, -0.2, 1.0, 0.0,
0.6, 0.0, 0.0, 1.0 ),
nrow=4, ncol=4)
Cholesky-decomposition
L = chol(M)
nvars = dim(L)[1]
Random variables:
r = t(L) %*% matrix(rnorm(nvars * megf), nrow=nvars, ncol=megf)
r = t(r)
It worked with positive correlations, but I also need negative. Why doesn't it work? How can I do that?
Best Answer
Your correlation matrix is not positive definite. This means that it is not possible for a real dataset to have generated it.
This works and has a negative correlation:
Your code doesn't run, because
megf
doesn't get defined.You can save a little effort by using the
mvrnorm()
function, in the MASS package.