模拟相关伯努利数据

Simulating correlated Bernoulli data

我想用 5 列模拟 100 个数据。我想在列之间获得 0.5 的相关性。为了完成它,我做了以下操作

F1 <- matrix( c(1, .5, .5, .5,.5,
                   .5, 1, .5, .5,.5,
                   .5, .5, 1, .5,.5,
                   .5, .5, .5, 1,.5,
                   .5, .5, .5, .5,1
), 5,5)

为了模拟预期的数据框,我已经这样做了,但是它不能正常工作。

 df2 <- as.data.frame (rbinom(100, 1,.5),ncol(5), F1)

我很惊讶这不是重复的(this question refers specifically to non-binary responses, i.e. binomial with N>1). The bindata package 做你想做的事。

library(bindata)
## set up correlation matrix (compound-symmetric with rho=0.5)
m <- matrix(0.5,5,5)
diag(m) <- 1

以 0.5 的平均值进行模拟(如您的示例所示):

set.seed(101)
## this simulates 10 rather than 100 realizations
## (I didn't read your question carefully enough)
## but it's easy to change
r <- rmvbin(n=10, margprob=rep(0.5,5), bincorr=m)
round(cor(r),2)

结果

 1.00 0.22  0.80  0.05 0.22
 0.22 1.00  0.00  0.65 1.00
 0.80 0.00  1.00 -0.09 0.00
 0.05 0.65 -0.09  1.00 0.65
 0.22 1.00  0.00  0.65 1.00
  • 这看起来不对 - 相关性不完全是 0.5 - 但 平均而言 它们会是(当我采样 10,000 个向量而不是 10 个时,值的范围从大约 0.48 到0.51)。同样,如果您模拟了 10 个样本并计算了每个样本的相关矩阵,您应该会发现预期的(平均)相关矩阵是正确的。
  • 模拟具有相关性的值完全等于指定值要困难得多(而且不一定是你想做的,取决于应用程序)
  • 请注意,对于可行的均值向量和相关矩阵会有限制。例如,n×n 复合对称(等相关)矩阵的非对角线元素不能小于 -1/(n-1)。同样,对于一组给定的均值可能存在的相关性可能存在限制(这可能在技术参考中讨论过,我没有检查过)。

此方法参考

Leisch, Friedrich and Weingessel, Andreas and Hornik, Kurt (1998) On the generation of correlated artificial binary data. Working Papers SFB "Adaptive Information Systems and Modelling in Economics and Management Science", 13. SFB Adaptive Information Systems and Modelling in Economics and Management Science, WU Vienna University of Economics and Business, Vienna. https://epub.wu.ac.at/286/