简体   繁体   中英

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). I want to run the simulation 200 times. Somehow it doesn't feel right to add a second 'for' loop to create a list of matrices. 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:

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) ))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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