3
$\begingroup$

Possible Duplicate:
How to generate correlated random numbers (given means, variances and degree of correlation)?

I have been trying to generate two random variables with correlation of -0.9 but have not been successful. I have tried:

x1 <- rnorm(200, mean=0, sd=1)
x2 <- rnorm(200, mean=0, sd=1) 
z <- -0.9*x1+sqrt((1-(-0.9)))*x2
cor(x1,z)

But it did not work.

I tried also the ?mvrnorm function, but it did not work either. How I can get this done??

$\endgroup$

marked as duplicate by Andy W, gung, whuber Jan 25 '13 at 20:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ I don't know why mvrnorm didn't work, note that @user603 demonstrates its use properly. Note also that my answer at the linked thread provides a way of generating correlated numbers exactly along the lines you're going for here (although I agree that you don't need to re-invent the wheel). $\endgroup$ – gung Jan 25 '13 at 19:33
  • $\begingroup$ Your expression in your line of code for z is wrong. (Note that even when you get it right, the sample correlation will still vary somewhat from -0.9) $\endgroup$ – Glen_b Jan 26 '13 at 3:08
5
$\begingroup$

Don't re-invent the wheel!

library(MASS)
M<-matrix(-0.9,2,2)
diag(M)<-1
X<-mvrnorm(200,rep(0,2),M,empirical=TRUE)
cor(X)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.