全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
2364 2
2011-11-02
各位好:

请问如何生成三组uniform random variable (x, Y, Z)且Corr(X,Y)不等於零,Corr(X,Z)不等於零,Corr(Y,Z)不等於零?谢谢

下面为生成两组correlation不等於零的uniform random variable。
This can be implemented by the following code:  n  <- 100  p  <- 0.6            # (say)  X  <- runif(n)-1/2  Z  <- runif(n)-1/2  U  <- rbinom(n,1,p)  # =1 where Y=X, = 0 when Y independent of X  Y  <- X*U + Z*(1-U)  XY <- cbind(X,Y)     # your n by 2 matrix of bivariate (X,Y)Now the marginal distributions of X and Y are both uniform.var(X) = 1/12 and var(Y) = 1/12. Since the means are 0,cov(X,Y) = Exp(X*Y) = p*Exp(X^2) = p/12cor(X,Y) = cov(X,Y)/sqrt(var(X)*var(Y)) = (p/12)/(1/12) = p.So all you need to do to get a desired correlation rho betweenX and Y is to set p = rho.



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2011-11-2 19:13:00
# generate normals, check correlations
X <- array(rnorm(9000), dim = c(3000, 3))
cor(X)
# desired correlation
M <- c(1.0, 0.9, 0.6, 0.9, 1.0, 0.3, 0.6, 0.3, 1.0)
dim(M) <- c(3,3)
M
#     [,1] [,2] [,3]
#[1,]  1.0  0.9  0.6
#[2,]  0.9  1.0  0.3
#[3,]  0.6  0.3  1.0
# adjust correlations for uniforms
for (i in 1:3){
    for (j in 1:3){
        if (i != j){
            M[i, j] <- 2 * sin(pi * M[i, j] / 6)
            M[j, i] <- 2 * sin(pi * M[j, i] / 6)
        }
    }
}
# induce correlation, check correlations
C <- chol(M)
Y <- X %*% C
cor(Y)
# create uniforms, check correlations
Y <- pnorm(Y)
cor(Y)
x=Y[,1]
y=Y[,2]
z=Y[,3]
cor(x,y)    #0.9102382
cor(y,z)    #0.3213543
cor(x,z)    #0.6197905
# plot results (marginals)
par(mfrow = c(1,3))
hist(x, main = paste("x"), xlab = "")
hist(y, main = paste("y"), xlab = "")
hist(z, main = paste("z"), xlab = "")
   hist.jpeg


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2011-11-2 22:17:13
epoh 发表于 2011-11-2 19:13
# generate normals, check correlations
X
很详细,谢谢。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群