3

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??

Karl
  • 31
  • 2
  • I don't know why `mvrnorm` didn't work, note that @user603 [demonstrates](http://stats.stackexchange.com/questions/48534/how-to-generate-two-negatively-correlated-random-series-of-numbers/48535#48535) 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). – gung - Reinstate Monica Jan 25 '13 at 19:33
  • 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) – Glen_b Jan 26 '13 at 03:08

1 Answers1

5

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)
user603
  • 21,225
  • 3
  • 71
  • 135