如何在R中创建具有特定相关性的正常随机变量?

要创建具有特定相关性的正常随机变量,我们可以使用MASS包的mvrnorm函数。例如,如果我们要创建两个大小为10的变量,其均值等于2和4,标准差为0.5,则可以使用以下命令来完成-

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

例1

library(MASS)

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

X

输出结果
       [,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

例2

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

Y

输出结果
       [,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

范例3

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

Z

输出结果
        [,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

以上是 如何在R中创建具有特定相关性的正常随机变量? 的全部内容, 来源链接: utcz.com/z/348397.html

回到顶部