# [R] simulation data in SEM

thanoon younis thanoon.younis80 at gmail.com
Sun Sep 14 15:56:34 CEST 2014

```Dear R members
I want to simulate data depending on SEM and when i applied the code below
i found some errors and i still cannot run it.

Thanoon

#Do simulation for 100 replications
N<-1000; P<-10

phi<-matrix(data=c(1.0,0.3,0.3,1.0),ncol=2) #The covariance matrix of xi
Ro<-matrix(data=c(7.0,2.1,2.1,7.0), ncol=2)
yo<-matrix(data=NA,nrow=N,ncol=P) p<-numeric(P); v<-numeric(P)

for (t in 1:100) {
#Generate the data for the simulation study
for (i in 1:N) {
#Generate xi
xi<-mvrnorm(1,mu=c(0,0),phi)
#Generate the fixed covariates
co<-rnorm(1,0,1)
#Generate error term is structural equation
delta<-rnorm(1,0,sqrt(0.3))
#Generate eta1 according to the structural equation
eta<-0.8*co[i]+0.6*xi[1]+0.6*xi[2]+0.8*xi[1]*xi[2]+delta
#Generate error terms in measurement equations
eps<-rnorm(3,0,1)

#Generate theta according to measurement equations
v1[1]<-1.0+eta+eps[1]; v1[2]<-1.0+0.7*eta+eps[2]
v1[3]<-1.0+0.7*eta+eps[3]
v1[4]<-1.0+xi[1]; v1[5]<-1.0+0.8*xi[1]; v1[6]<-1.0+0.8*xi[1]
v1[7]<-1.0+xi[2]; v1[8]<-1.0+0.7*xi[2]; v1[9]<-1.0+0.7*xi[2];
v1[10]<-1.0+0.7*xi1[2]

#transform theta to orinal variables
for (j in 1:10) { if (v[j]>0) yo[i,j]<-1 else yo[i,j]<-0 }

#Input data set for WinBUGS
data<-list(N=200,P=10,R=Ro,z=yo)

}   #end

[[alternative HTML version deleted]]

```