[英]Generate uncorrelated variables each well correlated with existing response variable
我想生成兩個不相關的隨機變量( x1,x2 ),它們顯示與現有變量y的指定Pearson相關性,例如:
因此,我有y的連續值(正態分布)(使用空間插值技術),現在我想使用上述相關系數為兩個解釋變量x1和x2生成模擬的連續值(例如,正態分布)。 我嘗試了mvrnorm(MASS)和copula R軟件包,但沒有找到做我想要的方法。
如果有人可以幫助我到達那里,我將非常感激。 親切的問候。
MASS軟件包中的mvrnorm
函數應該能夠做到這一點(copula軟件包也是如此,我對此不太熟悉)。
您嘗試了什么,結果與預期的有何不同?
這是一個快速的mvrnorm
示例:
> ?MASS::mvrnorm
> library(MASS)
>
> r <- cbind( c(1, 0.4, 0.3),
+ c(0.4, 1, 0.03),
+ c(0.3, 0.03, 1))
>
> xy <- mvrnorm(n=100, mu=c(0,0,0), Sigma=r, empirical=TRUE )
> colnames(xy) <- c('y','x1','x2')
>
> cor(xy)
y x1 x2
y 1.0 0.40 0.30
x1 0.4 1.00 0.03
x2 0.3 0.03 1.00
>
編輯
這是使用現有y變量的一種方法:
y <- rnorm(100) # existing y
# generate x1 and x2, make sure y is first column
xy <- cbind( y, x1=rnorm(100), x2=rnorm(100))
# center and scale
mns <- apply(xy, 2, mean)
sds <- apply(xy, 2, sd)
xy2 <- sweep(xy, 2, mns, FUN="-")
xy2 <- sweep(xy2, 2, sds, FUN="/")
# find existing correlations
v.obs <- cor(xy2)
# remove correlation
xy3 <- xy2 %*% solve(chol(v.obs))
# check
zapsmall(cor(xy3))
# new correlation
r <- cbind( c(1, 0.4, 0.3),
c(0.4, 1, 0.03),
c(0.3, 0.03, 1))
xy4 <- xy3 %*% chol(r)
# undo center and scale
xy4 <- sweep(xy4, 2, sds, FUN="*")
xy4 <- sweep(xy4, 2, mns, FUN="+")
#check
cor(xy4)
all.equal(y, xy[,1])
mvrnorm
函數使用svd
和Eigen值代替chol
。 您也可以使用自己的y而不是矩陣那部分的隨機值來遵循該代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.