| sem | R Documentation |
Variable names, raw data column names, and ordinary parameter labels must not contain periods. Rename consistently, e.g., x.1 to x_1, and check for duplicate names. Definition-variable references such as data.x_1 and group or cluster values containing periods are allowed.
It fits a structural equation model by creating a mxModel from a RAM object.
sem(model.name = "sem", RAM = NULL, data = NULL,
Cov = NULL, means = NULL, numObs, intervals.type = c("z",
"LB"), startvalues = NULL, lbound = NULL, ubound = NULL,
replace.constraints = FALSE, mxModel.Args = NULL,
run = TRUE, silent = TRUE, group = NULL, cluster = NULL,
...)
create.mxModel(model.name = "sem", RAM = NULL, data = NULL,
Cov = NULL, means = NULL, numObs, intervals.type = c("z",
"LB"), startvalues = NULL, replace.constraints = FALSE,
mxModel.Args = NULL, run = TRUE, silent = TRUE,
...)
model.name |
A string for the model name in
|
RAM |
A RAM object including a list of matrices of the model returned
from |
data |
A data frame or matrix of data. |
Cov |
If |
means |
Means corresponding to |
numObs |
Sample sizes corresponding to |
intervals.type |
Either |
startvalues |
A list of named starting values of the free parameters, e.g., list(a=1, b=2) |
lbound |
A list of lower bound of the free parameters. If it is not
provided, all free parameters are assumed |
ubound |
A list of upper bound of the free parameters. If it is not
provided, all free parameters are assumed |
replace.constraints |
Logical. If |
mxModel.Args |
A list of arguments passed to
|
run |
Logical. If |
silent |
Logical. Passed to |
group |
For combined group and cluster summary inputs, group and cluster must name different columns. A character string naming the column in |
cluster |
A character string naming the column in |
... |
Further arguments will be passed to either
|
Two-level models. A manifest variable appearing at both levels
is internally split into within and between components. Consequently, a
level-1 regression uses only the predictor's within component, as in
lavaan. Two-level summary input requires separate means,
covariance matrices, and sample sizes for each cluster; a pooled
covariance matrix cannot identify within- and between-cluster variation.
For complete Gaussian data these summaries reproduce the raw-data
likelihood. Combined group and two-level models use nested
group:/level: lavaan syntax and both group and
cluster arguments. replace.constraints=TRUE is supported
for two-level models (substituting a constraint into whichever of the
within-/between-level A/S/M matrices contains it,
including a constraint that spans both levels); a definition variable
(data.*) may be used in such a constraint at either level if its
between-level values are constant within each cluster. Cluster-level
observed covariates likewise require a constant value within each
cluster. The reported number of observations and the information
criteria use the number of level-1 rows with at least one observed
level-1 variable, as in lavaan. A cluster with a measured
between-level variable still contributes, even if all its level-1 data
are missing.
Constraints. Models with constraints between parameters
(==, <, or >) are fitted with an OpenMx
feasibility tolerance of 1e-6 unless one has been set with
mxOption(), and their model-based standard errors are computed
from the Hessian of the Lagrangian of -2LL and the constraints that hold
at the estimates instead of being taken from OpenMx. They equal those of
the same model with the constraints substituted
(replace.constraints=TRUE); for nonlinear constraints they can
differ from lavaan's, which omit the curvature of the constraints.
Robust standard errors. With a single-level model and no
cluster, robust covariance uses the observation-level sandwich of
OpenMx's imxRobustSE(), whose meat is multiplied by N/(N-1).
With cluster, it sums the row scores within clusters before
forming the sandwich and multiplies the meat by G/(G-1), where
G is the number of clusters, as lavaan does for
single-group models; this allows within-cluster dependence. With one row
per cluster it equals the robust covariance without cluster. For
flat multiple-group models, the same cluster ID in different groups
denotes the same independent unit; use distinct IDs when groups contain
distinct clusters. The bread uses the observed information, so it
matches lavaan with information="observed";
lavaan's default for cluster=, the expected information,
can give much smaller standard errors with data missing at random (see
clusterRobustSE). The optional smallSample=TRUE in
summary() or vcov() also multiplies the meat by
(N-1)/(N-p), where N is the number of rows and p the
number of free parameters (including those determined by constraints or
at a bound), for a total factor of G/(G-1) \cdot (N-1)/(N-p). With
few independent clusters, summary(fit, robust=TRUE, t.df=) uses a
t reference distribution instead of z; see
summary for how to choose its degrees of freedom.
Row scores are computed by numerical differentiation of the row
likelihoods, so their cost hardly depends on the number of rows.
Parameters estimated at a binding bound have no valid robust covariance:
their robust standard errors are NA, with a warning, and the other
parameters treat them as fixed. A bound binds if the estimate would move
past it without the bound; an estimate merely close to a bound has the
usual robust standard error. A defined (:=) parameter has an
NA robust standard error if it depends on any bounded parameter.
Robust covariance also warns when the OpenMx status code is neither 0
nor 1, because the fit may not have converged.
For two-level fits, robust covariance uses each cluster's complete
relational-model likelihood score, without a G/(G-1) factor, as in
lavaan's two-level models. Each score needs one OpenMx run that
differentiates the cluster's likelihood numerically, which takes several
likelihood evaluations per free parameter, so computing time grows with
both the number of clusters and the number of parameters. In combined
group and two-level models, clusters are nested within groups: each
group's clusters are formed from that group's rows only, so a cluster ID
used in two groups denotes two different clusters, and a unit spanning
groups cannot be represented. sem() warns when an ID appears in
more than one group, and robust covariance stops with an error in that
case. Cluster IDs generated from summary input are prefixed by the
group's position (e.g., "2.5" for cluster 5 in the second
group) when they would otherwise repeat. Robust summaries require
intervals.type="z"; likelihood-based intervals are not robust.
An object of class mxsem
Mike W.-L. Cheung <mikewlcheung@nus.edu.sg>
## Generate data
set.seed(100)
n <- 100
x <- rnorm(n)
y <- 0.5*x + rnorm(n, mean=0, sd=sqrt(1-0.5^2))
my.df <- data.frame(y=y, x=x)
## A regression model
model <- "y ~ x # Regress y on x
y ~ 1 # Intercept of y
x ~ 1 # Mean of x"
plot(model)
RAM <- lavaan2RAM(model, obs.variables=c("y", "x"))
my.fit <- sem(RAM=RAM, data=my.df)
summary(my.fit)
## A meta-analysis
model <- "f =~ 1*yi
f ~ mu*1 ## Average effect
f ~~ tau2*f ## Heterogeneity variance
yi ~~ data.vi*yi ## Known sampling variance"
plot(model)
## Do not standardize the latent variable (f): std.lv=FALSE
RAM <- lavaan2RAM(model, obs.variables="yi", std.lv=FALSE)
## Use likelihood-based CI
my.fit <- sem(RAM=RAM, data=Hox02, intervals="LB")
summary(my.fit)
## A 2-group regression with a shared slope but group-specific intercepts
x1 <- rnorm(100); y1 <- 2 + 0.5*x1 + rnorm(100)
x2 <- rnorm(100); y2 <- -1 + 0.5*x2 + rnorm(100)
my.df2 <- data.frame(y=c(y1, y2), x=c(x1, x2),
g=rep(c("g1", "g2"), each=100))
model <- "y ~ c(b,b)*x + c(a1,a2)*1"
RAM <- lavaan2RAM(model, ngroups=2)
my.fit <- sem(RAM=RAM, data=my.df2, group="g")
summary(my.fit)
## The same 2-group regression, extended with replace.constraints=TRUE:
## group 2's residual variance is constrained to be exactly TWICE group
## 1's, and group 1's own residual variance is reparameterised through
## exp() (guaranteeing positivity). "resid1" never appears as a free
## parameter itself -- lavaanify() would otherwise reject "a0" as
## undeclared, and an ordinary (non-replaced) "==" constraint cannot
## introduce a new free parameter this way; only replace.constraints=
## TRUE can. The constraint chain is resolved across groups, so
## "resid2" ends up expressed directly in terms of "a0" (not "resid1").
model <- "y ~ c(b,b)*x + c(a1,a2)*1
y ~~ c(resid1,resid2)*y
resid1 == exp(a0)
resid2 == 2*resid1"
RAM <- lavaan2RAM(model, ngroups=2)
my.fit <- sem(RAM=RAM, data=my.df2, group="g", replace.constraints=TRUE)
summary(my.fit)
## A two-level (random-intercept) regression model
set.seed(123)
nClusters <- 60; nPerCluster <- 6
clusterID <- rep(seq_len(nClusters), each=nPerCluster)
u <- rep(rnorm(nClusters, 0, 0.7), each=nPerCluster)
x <- rnorm(nClusters*nPerCluster)
y <- 1.5 + 0.6*x + u + rnorm(nClusters*nPerCluster)
my.df3 <- data.frame(clusterID=clusterID, x=x, y=y)
model <- "level: 1
y ~ b1*x
y ~~ residW*y
level: 2
y ~ 1
y ~~ residB*y"
RAM <- lavaan2RAM(model)
my.fit <- sem(RAM=RAM, data=my.df3, cluster="clusterID")
summary(my.fit)
## A 2-group CFA: test whether factor loadings are invariant across groups
set.seed(103)
simGroup <- function(n, loadings) {
f <- rnorm(n)
Y <- sapply(loadings, function(l) l*f + rnorm(n, sd=0.5))
colnames(Y) <- paste0("y", seq_along(loadings))
data.frame(Y)
}
loadings <- c(1, 0.8, 1.3, 0.9)
my.df4 <- rbind(cbind(simGroup(250, loadings), g="g1"),
cbind(simGroup(250, loadings), g="g2"))
## Metric invariance: loadings constrained equal across groups.
## std.lv=FALSE: the factor's scale is already identified by fixing
## y1's loading at 1 (c(1,1)*y1), so its variance ("f ~~ c(vf1,vf2)*f")
## is left free and group-specific instead of also being fixed at 1 --
## lavaan2RAM()'s default std.lv=TRUE would otherwise silently discard
## that "f ~~ ..." line, fixing the variance at 1 in both groups with
## no error (see lavaan2RAM()'s "std.lv" argument for details).
model.invariant <- "f =~ c(1,1)*y1 + c(l2,l2)*y2 + c(l3,l3)*y3 + c(l4,l4)*y4
f ~~ c(vf1,vf2)*f
y1 ~ c(m1a,m1b)*1
y2 ~ c(m2a,m2b)*1
y3 ~ c(m3a,m3b)*1
y4 ~ c(m4a,m4b)*1"
fit.invariant <- sem(RAM=lavaan2RAM(model.invariant, ngroups=2, std.lv=FALSE),
data=my.df4, group="g")
## Configural model: loadings free in each group
model.free <- "f =~ c(1,1)*y1 + c(l2a,l2b)*y2 + c(l3a,l3b)*y3 + c(l4a,l4b)*y4
f ~~ c(vf1,vf2)*f
y1 ~ c(m1a,m1b)*1
y2 ~ c(m2a,m2b)*1
y3 ~ c(m3a,m3b)*1
y4 ~ c(m4a,m4b)*1"
fit.free <- sem(RAM=lavaan2RAM(model.free, ngroups=2, std.lv=FALSE),
data=my.df4, group="g")
summary(fit.invariant)
anova(fit.free, fit.invariant) # likelihood-ratio test of metric invariance
## Group difference in the factor variance, as a derived quantity
model.diff <- paste(model.free, "\ndiff_v := vf2 - vf1")
fit.diff <- sem(RAM=lavaan2RAM(model.diff, ngroups=2, std.lv=FALSE),
data=my.df4, group="g")
summary(fit.diff) # see "Mxalgebras" in the printed output for diff_v
## A two-level CFA: a factor at the within level and another at the
## between level, with the same three indicators loading on both
set.seed(104)
nClusters <- 100; nPerCluster <- 8; N <- nClusters*nPerCluster
clusterID <- rep(seq_len(nClusters), each=nPerCluster)
fb <- rep(rnorm(nClusters, 0, 1), each=nPerCluster)
fw <- rnorm(N, 0, 1)
ly2 <- 0.8; ly3 <- 1.2
y1 <- fb + fw + rnorm(N, 0, 0.5)
y2 <- ly2*fb + ly2*fw + rnorm(N, 0, 0.5)
y3 <- ly3*fb + ly3*fw + rnorm(N, 0, 0.5)
my.df5 <- data.frame(clusterID=clusterID, y1=y1, y2=y2, y3=y3)
model <- "level: 1
fw =~ y1 + y2 + y3
level: 2
fb =~ y1 + y2 + y3"
RAM <- lavaan2RAM(model)
my.fit <- sem(RAM=RAM, data=my.df5, cluster="clusterID")
summary(my.fit)
## A two-level (multilevel) meta-analysis: studies contributing several
## dependent effect sizes each, separating within- from between-study
## heterogeneity while accounting for each effect size's own known
## sampling variance
set.seed(106)
nStudies <- 60
esPerStudy <- sample(2:4, nStudies, replace=TRUE)
studyID <- rep(seq_len(nStudies), esPerStudy)
N <- length(studyID)
mu <- 0.35; tau2.between <- 0.03; tau2.within <- 0.015
studyEffect <- rep(rnorm(nStudies, mu, sqrt(tau2.between)), esPerStudy)
vi <- runif(N, 0.02, 0.06)
yi <- rnorm(N, studyEffect + rnorm(N, 0, sqrt(tau2.within)), sqrt(vi))
my.df6 <- data.frame(studyID=studyID, yi=yi, vi=vi)
## fw's own variance is the WITHIN-study heterogeneity; yi's own residual
## (after removing fw) is fixed at the KNOWN sampling variance; the
## BETWEEN-study heterogeneity is yi's own variance at level 2
model <- "level: 1
fw =~ 1*yi
fw ~~ tauW*fw
yi ~~ data.vi*yi
level: 2
yi ~ mu*1
yi ~~ tauB*yi"
RAM <- lavaan2RAM(model, std.lv=FALSE)
my.fit <- sem(RAM=RAM, data=my.df6, cluster="studyID")
summary(my.fit)
## A two-level location-scale meta-analysis: replace.constraints=TRUE
## lets the WITHIN-study heterogeneity (tauW, on fw) be a function of an
## effect-size-level moderator xi, while yi's own residual stays fixed
## at its KNOWN sampling variance (data.vi), exactly as in the previous
## example. data.xi is a definition variable, so its per-row value is
## looked up from the data instead of estimated. "tauW" never appears
## as a free parameter itself here -- lavaanify() would otherwise reject
## a0/a1 as undeclared, and an ordinary (non-replaced) "==" constraint
## cannot introduce new free parameters this way; only
## replace.constraints=TRUE can.
set.seed(107)
xi <- rnorm(N)
a0 <- -4; a1 <- 0.8
tauWi <- exp(a0 + a1*xi)
yi2 <- rnorm(N, studyEffect + rnorm(N, 0, sqrt(tauWi)), sqrt(vi))
my.df7 <- data.frame(studyID=studyID, yi=yi2, vi=vi, xi=xi)
model <- "level: 1
fw =~ 1*yi
fw ~~ tauW*fw
yi ~~ data.vi*yi
level: 2
yi ~ mu*1
yi ~~ tauB*yi
tauW == exp(a0 + a1*data.xi)"
RAM <- lavaan2RAM(model, std.lv=FALSE)
my.fit <- sem(RAM=RAM, data=my.df7, cluster="studyID",
replace.constraints=TRUE)
summary(my.fit)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.