# How to generate two negatively correlated random series of numbers? [duplicate]

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

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

• 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). – gung 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 3:08

library(MASS)