【问题标题】:How to simulate a vector that is correlated (in a different way) to two other existing vectors如何模拟与其他两个现有向量相关(以不同方式)的向量
【发布时间】:2017-12-12 14:47:58
【问题描述】:

我想模拟一个与其他两个现有变量相关的向量。到目前为止我尝试了什么

# some correlation matrix
desiredCorrelations = matrix(c(1, .4, 0, 
                              .4, 1, .3,
                               0, .3, 1), nrow = 3)

# some simulated data based on the correlation matrix
dat = mvrnorm(n = 1000, mu = rep(3, 3), Sigma = desiredCorrelations, empirical = TRUE) 

n = nrow(dat)
k = ncol(desiredCorrelations)
x = matrix( rnorm(n*k), nc=k )
x[,1] = dat[,1]
y = x %*% solve(chol(var(x))) %*% chol(desiredCorrelations)
# cor(y)      # Desired correlation matrix

apply(dat, 2, summary)
apply(y, 2, summary)

根据这段代码,相关性是正确的,但只有 y 的第一列与原始模拟数据的第一列相同。但是,我希望两列保持不变,而第三列是在考虑所需相关矩阵的情况下进行模拟的。

提前感谢您的任何建议或提示!

【问题讨论】:

    标签: r simulate


    【解决方案1】:

    我为此编写了一个基于 MattBagg's code 的函数,它接受一个向量 x 并返回一个具有指定均值、标准差和相关性的向量:

    simcor <- function (x, ymean=0, ysd=1, correlation=0) {
        n <- length(x)
    
        y <- rnorm(n)
        z <- correlation * scale(x)[,1] + sqrt(1 - correlation^2) * 
             scale(resid(lm(y ~ x)))[,1]
        yresult <- ymean + ysd * z
        yresult
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2017-06-08
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多