How to generate correlated variables in R?

7

I was able to create the uniform variables X and W , both with normal distribution, through the formula rnorm and R . However, I wanted to create the variables so that they had a -0.8 correlation value.

What command is used for this?

    
asked by anonymous 23.03.2014 / 02:24

1 answer

3

There are at least two ways to do this:

  • Since the two variables are Normal, you can use the mvrnorm() function of the MASS package.

  • Another option is to follow these instructions:

    # gerar dois vetores N(0,1), independentes
    z1 = rnorm(100)
    z2 = rnorm(100)
    
    rho = -0.8  # o coeficiente de correlacao
    
    e1 = z1
    e2 = rho*z1+sqrt(1-rho^2)*z2
    
    cor(e1,e2)  # aproximadamente -0.8
    
  • Note however that solution 2 should be adapted if it is desired that the vectors e1 and e2 have means different from 0.

    The original question does not make it clear whether the X and W vectors follow the uniform or normal distribution; my answer assumes it's the 2nd case.

        
    23.03.2014 / 02:46