Skip to content

Instantly share code, notes, and snippets.

@cdriveraus
Created October 26, 2017 14:40
Show Gist options
  • Save cdriveraus/0b1bd02bc55e1e6c9fcbe42093cefbe1 to your computer and use it in GitHub Desktop.
Save cdriveraus/0b1bd02bc55e1e6c9fcbe42093cefbe1 to your computer and use it in GitHub Desktop.
Simple mediation example in ctsem - frequentist and hierarchical Bayes approaches.
install.packages('ctsem')
library(ctsem)
#generate data (columns of drift matrix 'cause' rows)
genmodel <- ctModel(n.manifest=3,n.latent=3,LAMBDA=diag(3),Tpoints=10,
DRIFT=matrix(c(
-.3, .1,0,
0,-.3,.1,
0,0,-.3), nrow=3, ncol=3),
DIFFUSION=diag(1,3))
dat <- ctGenerate(ctmodelobj=genmodel,n.subjects=50,burnin=50,wide=FALSE)
#specify full and mediated models (real data probably needs between person variance specification, eg:
#MANIFESTTRAITVAR='auto', or use Bayesian random effects approach below...
fullmodel <- ctModel(n.manifest=3,n.latent=3,LAMBDA=diag(3),Tpoints=10,
DRIFT=matrix(c(
'a11', 'a12','a13',
0,'a22','a23',
0,0,'a33'), nrow=3, ncol=3))
mediatedmodel <- ctModel(n.manifest=3,n.latent=3,LAMBDA=diag(3),Tpoints=10,
DRIFT=matrix(c(
'a11', 'a12',0,
0,'a22','a23',
0,0,'a33'), nrow=3, ncol=3))
#fit
fullfit <- ctFit(dat=dat,ctmodelobj=fullmodel,dataform='long')
mediatedfit <- ctFit(dat=dat,ctmodelobj=mediatedmodel,dataform='long')
#compare model fit
mxCompare(fullfit$mxobj,mediatedfit$mxobj)
#summarise
summary(mediatedfit)
plot(mediatedfit)
#use Bayesian approach with random effects instead (slower!)
bayesmediatedmodel<-ctStanModel(ctmodelobj=mediatedmodel)
bayesmediatedfit <- ctStanFit(datalong=dat,ctstanmodel=bayesmediatedmodel,iter=200,chains=3,cores=3)
plot(bayesmediatedfit)
summary(bayesmediatedfit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment