Reputation: 317
I am trying to run a multivariate simulation 100 times and would like to save each run in a new variable and write it to a new csv file. I am not sure how to loop this through.
I am able to save each run by duplicating the code and naming the variables manually. This is tedious and I am sure there is a better way to achieve this.
library(dmutate)
mu <- c(4.23, 3.01, 2.91)
stddev <- c(1.23, 0.92, 1.32)
corMat <- matrix(c(1, 0.78, 0.23,
0.78, 1, 0.27,
0.23, 0.27, 1),
ncol = 3)
covMat <- stddev %*% t(stddev) * corMat
sims1 <- rmvnorm(10000, mu = mu, covMat)
sims2 <- rmvnorm(10000, mu = mu, covMat)
sims3 <- rmvnorm(10000, mu = mu, covMat)
.
.
.
sims100 <- rmvnorm(10000, mu = mu, covMat)
write.csv(sims1, file = "Sims_out1.csv", row.names = FALSE)
write.csv(sims2, file = "Sims_out2.csv", row.names = FALSE)
write.csv(sims3, file = "Sims_out3.csv", row.names = FALSE)
I'd like to loop them and save them as different variables and write them into different csv files without having to copy them over a 100 times manually.
Upvotes: 1
Views: 90
Reputation: 506
looking at your example I would do this.
for (i in 1:100) {
sims <- rmvnorm(10000, mu = mu, covMat)
write.csv(sims1, file = paste0("Sims_out",i,".csv"), row.names = FALSE)
}
Basically you want to for loop a simulation and then write it in a new file.
Upvotes: 1