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
和特徵值而不是chol
。你也可以使用你自己的y來代替那個矩陣的那部分的隨機值。
@ManuelCR,使用現有的y變量使其更難一點,看到我的編輯上面的一種方法來做到這一點。 –
謝謝。 'mvrnorm'和'copula'完成這項工作,但是兩者都不能使用自己的數據(變量y,就我而言)。我的變量y具有空間依賴值(更接近的觀察值往往更類似),我想保留這個值。我想要的是添加兩個其他變量,以提供完整的數據集,其中相關矩陣是指示的那個。 –