简体   繁体   English

如何从多元正态分布模拟R中的200个矩阵(20 * 100)?

[英]How can I simulate 200 matrices (20*100) in R from a multivariate normal distribution?

I'm using the following code to simulate 20 observations for 100 predictor variables (features). 我正在使用以下代码模拟100个预测变量(功能)的20个观察值。 I want to run the simulation 200 times. 我想运行200次模拟。 Somehow it doesn't feel right to add a second 'for' loop to create a list of matrices. 不知何故添加第二个“ for”循环来创建矩阵列表是不合适的。 Do you have any suggestions on how to efficiently simulate several matrices from a multivariate normal distribution? 您是否对如何从多元正态分布中有效地模拟几个矩阵有任何建议?

x <- matrix(rep(NA, 20*100), 20, 100)
for (i in 1:20) {
    x[i, ] <- mvrnorm(n = 1, mu = rep(0, 100), Sigma = diag(100)) 
}

Thank you! 谢谢!

If you really need no correlation, simply use 如果您真的不需要关联,只需使用

x = array( rnorm(200*20*100), dim=c(200,20,100) )

Your code could be abbreviated to 您的代码可以缩写为

library(mvtnorm)
x <- rmvnorm( n=20, mean=rep(0,100), sigma=diag(100) )

Now in order to have 200 of such matrices, I suggest the outer 'for' loop: 现在,为了拥有200个这样的矩阵,我建议使用外部“ for”循环:

x <- array( dim=c(200,20,100) )
for (i in 1:200) {
  x[i,,] <- rmvnorm( n=20, mean=rep(0,100), sigma=diag(100) )
}
lapply(1:200,function(x) rmvnorm( n=20, mean=rep(0,100), sigma=diag(100) ))

将为您提供此类矩阵的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM