# Create simulated path model dataset and save to CSV [closed]

I am teaching a multivariate stats class and wanted to give people some simulated datasets with mediation, path modeling, and other features. I know it's possible to run monte carlo studies in MPlus, but does anyone know any good ways to save a single such dataset to a CSV file? Or how to do it in R? I was hoping to specify a set of multivariate relationships, means, and SDs, and then create the CSV file.

• Although this is asked in terms of R, if you understand the underlying statistical ideas, the problem (& the code) would be trivial. Hence, I think we could treat this as a statistical (ie on-topic). – gung - Reinstate Monica May 5 '15 at 0:55

Use the mvrnorm function in the MASS package to get a multivariate normal distribution (it comes with base R).

Here's some example code:

library(MASS)
library(ggplot2) # used for plotting, otherwise, it's optional
Sigma <- matrix(c(10,3,3,2),2,2)
var(mvrnorm(n = 1000, rep(0, 2), Sigma))
example <- mvrnorm(n = 1000, rep(0, 2), Sigma)

examplePlot <- qplot(example[,1], example[,2]) +
xlab(expression(x)) +
ylab(expression(x))

ggsave("examplePlot.jpg", examplePlot, width = 4, height = 4)
write.csv(x =  example, file = "example.csv",  row.names = FALSE)


That produces this figure: To learn more aboutmvrnorm, type ?mvrnorm to view its help file. Also, many functions in include examples. So, when you find your multivariate analysis functions, type: example(...) and often R will show you how to use it.

Good with your course! Also, if you include the specific types of analysis you are trying to do, we could provide better tips.