use*_*054 5 simulation statistics r distribution correlation
假设X~exp(.67),Y~exp(.45)和Z~exp(.8).现在X与相关Y,相关系数-0.6.同样,X与相关Z,相关系数-0.6.我怎样才能将这一相关性来产生随机变量X,Y和Z?我知道如果它们之间没有相关性,那么我可以简单地生成数据X <- rexp(n=10, rate=.67),Y <- rexp(10, .45)和Z <- rexp(10, .8).
为此,您可以使用包中的Iman 和 Conover 方法mc2d。
首先,创建您的设置。鉴于没有上述相关性,我假设 Y 和 Z 不相关。(如果不是,只需相应地更改相关矩阵即可。)
library(mc2d)
x1 <- rexp(n = 1000, rate = 0.67)
x2 <- rexp(n = 1000, rate = 0.45)
x3 <- rexp(n = 1000, rate = 0.8)
mat <- cbind(x1, x2, x3)
corr <- matrix(c(1, -0.6, -0.6, -0.6, 1, 0, -0.6, 0, 1), ncol=3)
Run Code Online (Sandbox Code Playgroud)
我们现在可以测试随机样本的实际相关性……正如预期的那样,所有这些看起来都是独立的。
cor(mat, method="spearman")
Run Code Online (Sandbox Code Playgroud)
...生成:
x1 x2 x3
x1 1.00000000 0.01602557 -0.0493488
x2 0.01602557 1.00000000 0.0124209
x3 -0.04934880 0.01242090 1.0000000
Run Code Online (Sandbox Code Playgroud)
我们现在将Iman 和 Conover 方法应用于数据。
matc <- cornode(mat, target=corr, result=TRUE)
Run Code Online (Sandbox Code Playgroud)
这样做会产生以下相关性:
Spearman Rank Correlation Post Function
x1 x2 x3
x1 1.0000000 -0.59385975 -0.56201396
x2 -0.5938597 1.00000000 -0.04115543
x3 -0.5620140 -0.04115543 1.00000000
Run Code Online (Sandbox Code Playgroud)
最后,通过运行head(matc),我们可以看到修改后的示例的初始行:
x1 x2 x3
[1,] 1.1375395 0.3081750 2.26850817
[2,] 2.9387996 0.4434207 0.08940867
[3,] 1.0918648 0.4175625 2.29498679
[4,] 10.0273879 1.1478072 0.16099230
[5,] 1.5093832 0.4023230 2.57870672
[6,] 0.9474039 2.1134685 0.95268424
Run Code Online (Sandbox Code Playgroud)