Search code examples
rcorrelationmontecarlo

Monte Carlo Simulation to generate two related variables in R


I am looking for a way to generate two related variables from a normal distribution with Monte Carlo simulation using R. Specifically, I want to define different correlations between these two variables (i.e., r = .30, .60, .90). Thanks a lot!


Solution

  • You can use rnorm_multi() from the faux package:

    library("faux")
    
    x <- rnorm_multi(n = 1000, vars = 2, r = 0.9)
    cor.test(x$X1, x$X2)
    #> 
    #>  Pearson's product-moment correlation
    #> 
    #> data:  x$X1 and x$X2
    #> t = 65.537, df = 998, p-value < 2.2e-16
    #> alternative hypothesis: true correlation is not equal to 0
    #> 95 percent confidence interval:
    #>  0.8884275 0.9118777
    #> sample estimates:
    #>       cor 
    #> 0.9008074