How to create normal random variables with specific correlation between them in R?

R ProgrammingServer Side ProgrammingProgramming

To create normal random variables with specific correlation between them, we can use mvrnorm function of MASS package. For example, if we want to create two variables of size 10 with means equal to 2 and 4 and standard deviation of 0.5 then it can be done by using the command −

mvrnorm(10,mu=c(2,4),Sigma=matrix(c(1,0.5,0.5,1),ncol=2),empirical=TRUE)

Example1

library(MASS)
X<-mvrnorm(20,mu=c(5,6),Sigma=matrix(c(1,0.97,0.97,1),ncol=2),empirical=TRUE)
X

Output

       [,1]       [,2]
[1,]  4.734045  5.860623
[2,]  3.844051  4.920516
[3,]  4.387584  5.769242
[4,]  5.720935  6.694407
[5,]  5.749076  6.905320
[6,]  4.814826  5.649758
[7,]  5.320584  6.716148
[8,]  5.791732  6.629848
[9,]  6.234083  7.088140
[10,] 4.209064  5.523264
[11,] 4.658825  5.334275
[12,] 6.499547  7.302753
[13,] 6.296104  6.828497
[14,] 4.203930  5.353094
[15,] 3.679087  4.464786
[16,] 3.547234  4.457977
[17,] 6.116487  7.273061
[18,] 4.872711  5.646771
[19,] 3.395766  4.340987
[20,] 5.924329  7.240531

cor(X)

     [,1]  [,2]
[1,] 1.00  0.97
[2,] 0.97  1.00

Example2

Y<-mvrnorm(20,mu=c(100,120),Sigma=matrix(c(1,-0.78,-0.78,1),ncol=2),empirical=TRUE)
Y

Output

       [,1]        [,2]
[1,]  100.35035  119.5481
[2,]  98.80491   121.2622
[3,]  100.70750  118.3223
[4,]  100.87404  119.8765
[5,]  101.06911  119.1632
[6,]  99.80321   119.5711
[7,]  98.89158   120.5820
[8,]  98.63285   121.2333
[9,]  100.98014  120.7017
[10,] 98.20288   120.8348
[11,] 98.96695   121.0503
[12,] 99.97610   120.4775
[13,] 99.96563   119.2600
[14,] 100.59370  119.1507
[15,] 100.66358  119.3445
[16,] 101.25303  119.4787
[17,] 100.59732  119.3951
[18,] 99.67970   119.8449
[19,] 101.37637  118.6709
[20,] 98.61106   122.2320

cor(Y)

[,1] [,2]
[1,] 1.00 -0.78
[2,] -0.78 1.00

Example3

Z<-mvrnorm(20,mu=c(1,1),Sigma=matrix(c(1,-0.40,-0.40,1),ncol=2),empirical=TRUE)
Z

Output

        [,1]           [,2]
[1,]   0.344030694   1.10411548
[2,]   0.922039529   0.24012450
[3,]   0.631725557   2.00128990
[4,]   2.229289991  -0.50200549
[5,]   1.180211078   1.99181844
[6,]   1.012940481   1.49396082
[7,]   2.506394541   1.11997765
[8,]   1.019857403  -0.04125523
[9,]  -0.004349292  -0.04837025
[10,] -0.770750258   2.35083803
[11,] -0.368335882   1.29590311
[12,]  1.338721298   2.92684775
[13,]  0.378076422   1.72233721
[14,]  2.650859368  -0.81180597
[15,]  1.355467066   0.37518755
[16,]  2.500790061   0.72880980
[17,] -0.619248618   1.58565187
[18,]  0.924785938  -0.10665410
[19,]  1.196351320   1.06036152
[20,]  1.571143303   1.51286741

cor(Z)

      [,1]  [,2]
[1,] 1.0  -0.4
[2,] -0.4  1.0
raja
Published on 06-Mar-2021 13:42:13
Advertisements