Title: | Structural Equation Models |
---|---|
Description: | Functions for fitting general linear structural equation models (with observed and latent variables) using the RAM approach, and for fitting structural equations in observed-variable models by two-stage least squares. |
Authors: | John Fox [aut], Zhenghua Nie [aut, cre], Jarrett Byrnes [aut], Michael Culbertson [ctb], Saikat DebRoy [ctb], Michael Friendly [ctb], Benjamin Goodrich [ctb], Richard H. Jones [ctb], Adam Kramer [ctb], Georges Monette [ctb], Frederick Novomestky [ctb], R-Core [ctb] |
Maintainer: | Zhenghua Nie <[email protected]> |
License: | GPL (>= 2) |
Version: | 3.1-16 |
Built: | 2024-10-28 07:02:41 UTC |
Source: | CRAN |
This data set includes four measures of democracy at two points in time, 1960 and 1965, and three measures of industrialization in 1960, for 75 developing countries.
Bollen
Bollen
A data frame with 75 observations on the following 11 variables.
y1
freedom of the press, 1960
y2
freedom of political opposition, 1960
y3
fairness of elections, 1960
y4
effectivness of elected legislature, 1960
y5
freedom of the press, 1965
y6
freedom of political opposition, 1965
y7
fairness of elections, 1965
y8
effectivness of elected legislature, 1965
x1
GNP per capita, 1960
x2
energy consumption per capita, 1960
x3
percentage of labor force in industry, 1960
Variables y1
through y4
are intended to be indicators of the latent variable political democracy in 1960;
y5
through y8
indicators of political democracy in 1965; and
x1
through x3
indicators of industrialization in 1960.
personal communication from Ken Bollen.
Bollen, K. A. (1989) Structural Equations With Latent Variables. Wiley.
Bootstraps a structural equation model in an sem
object (as returned by
the sem
function).
bootSem(model, ...) ## S3 method for class 'sem' bootSem(model, R=100, Cov=cov, data=model$data, max.failures=10, show.progress=TRUE, ...) ## S3 method for class 'msem' bootSem(model, R=100, Cov=cov, data=model$data, max.failures=10, show.progress=TRUE, ...) ## S3 method for class 'bootsem' print(x, digits=getOption("digits"), ...) ## S3 method for class 'bootsem' summary(object, type=c("perc", "bca", "norm", "basic", "none"), level=0.95, ...)
bootSem(model, ...) ## S3 method for class 'sem' bootSem(model, R=100, Cov=cov, data=model$data, max.failures=10, show.progress=TRUE, ...) ## S3 method for class 'msem' bootSem(model, R=100, Cov=cov, data=model$data, max.failures=10, show.progress=TRUE, ...) ## S3 method for class 'bootsem' print(x, digits=getOption("digits"), ...) ## S3 method for class 'bootsem' summary(object, type=c("perc", "bca", "norm", "basic", "none"), level=0.95, ...)
model |
an |
R |
the number of bootstrap replications; the default is 100, which should be enough for computing standard errors, but not confidence intervals (except for the normal-theory intervals). |
Cov |
a function to compute the input covariance or moment matrix; the default is
|
data |
in the case of a |
max.failures |
maximum number of consecutive convergence failures before |
show.progress |
display a text progress bar on the console tracing the bootstrap replications. |
x , object
|
an object of class |
digits |
controls the number of digits to print. |
type |
type of bootstrapped confidence intervals to compute; the
default is |
level |
level for confidence intervals; default is |
... |
in |
bootSem
implements the nonparametric bootstrap, assuming an
independent random sample. Convergence failures in the bootstrap resamples
are discarded (and a warning printed); more than max.failures
consecutive convergence failures (default, 10)
result in an error. You can use the boot
function
in the boot package for more complex sampling schemes and additional options.
Bootstrapping is implemented by resampling the observations in
data
, recalculating the input covariance matrix with Cov
,
and refitting the model with sem
, using the
parameter estimates from the original sample as start-values.
Warning: the bootstrapping process can be very time-consuming.
bootSem
returns an object of class bootsem
, which inherits
from class boot
, supported by the boot package. The returned
object contains the following components:
t0 |
the estimated parameters in the model fit to the original data set. |
t |
a matrix containing the bootstrapped estimates, one bootstrap replication per row. |
data |
the data to which the model was fit. |
seed |
the value of |
statistic |
the function used to produce the bootstrap replications;
this is always the local function |
sim |
always set to |
stype |
always set to |
call |
the call of the |
weights |
a vector of length equal to the number of observations |
strata |
a vector of length |
John Fox [email protected]
Davison, A. C., and Hinkley, D. V. (1997) Bootstrap Methods and their Application. Cambridge.
Efron, B., and Tibshirani, R. J. (1993) An Introduction to the Bootstrap. Chapman and Hall.
## Not run: # because of long execution time # A simple confirmatory factor-analysis model using polychoric correlations. # The polycor package is required for the hetcor function. if (require(polycor)){ # The following function returns correlations computed by hetcor, # and is used for the bootstrapping. hcor <- function(data) hetcor(data, std.err=FALSE)$correlations model.cnes <- specifyModel(text=" F -> MBSA2, lam1 F -> MBSA7, lam2 F -> MBSA8, lam3 F -> MBSA9, lam4 F <-> F, NA, 1 MBSA2 <-> MBSA2, the1 MBSA7 <-> MBSA7, the2 MBSA8 <-> MBSA8, the3 MBSA9 <-> MBSA9, the4 ") R.cnes <- hcor(CNES) sem.cnes <- sem(model.cnes, R.cnes, N=1529) summary(sem.cnes) } # Note: this can take a minute: set.seed(12345) # for reproducibility system.time(boot.cnes <- bootSem(sem.cnes, R=100, Cov=hcor, data=CNES)) summary(boot.cnes, type="norm") # cf., standard errors to those computed by summary(sem.cnes) ## End(Not run) ## Not run: # because of long execution time # An example bootstrapping a multi-group model mod.hs <- cfa(text=" spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet ") mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) # Note: this example can take several minutes or more; # you can decrease R if you just want to see how it works: set.seed(12345) # for reproducibility system.time(boot.mg <- bootSem(sem.mg, R=100)) summary(boot.mg, type="norm") # cf., standard errors to those computed by summary(sem.mg) ## End(Not run)
## Not run: # because of long execution time # A simple confirmatory factor-analysis model using polychoric correlations. # The polycor package is required for the hetcor function. if (require(polycor)){ # The following function returns correlations computed by hetcor, # and is used for the bootstrapping. hcor <- function(data) hetcor(data, std.err=FALSE)$correlations model.cnes <- specifyModel(text=" F -> MBSA2, lam1 F -> MBSA7, lam2 F -> MBSA8, lam3 F -> MBSA9, lam4 F <-> F, NA, 1 MBSA2 <-> MBSA2, the1 MBSA7 <-> MBSA7, the2 MBSA8 <-> MBSA8, the3 MBSA9 <-> MBSA9, the4 ") R.cnes <- hcor(CNES) sem.cnes <- sem(model.cnes, R.cnes, N=1529) summary(sem.cnes) } # Note: this can take a minute: set.seed(12345) # for reproducibility system.time(boot.cnes <- bootSem(sem.cnes, R=100, Cov=hcor, data=CNES)) summary(boot.cnes, type="norm") # cf., standard errors to those computed by summary(sem.cnes) ## End(Not run) ## Not run: # because of long execution time # An example bootstrapping a multi-group model mod.hs <- cfa(text=" spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet ") mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) # Note: this example can take several minutes or more; # you can decrease R if you just want to see how it works: set.seed(12345) # for reproducibility system.time(boot.mg <- bootSem(sem.mg, R=100)) summary(boot.mg, type="norm") # cf., standard errors to those computed by summary(sem.mg) ## End(Not run)
These variables are from the mailback questionnaire to the 1997 Canadian National Election Study, and are intended to tap attitude towards “traditional values.”
CNES
CNES
A data frame with 1529 observations on the following 4 variables.
MBSA2
an ordered factor with levels StronglyDisagree
,
Disagree
, Agree
, and StronglyAgree
, in response to the statement,
“We should be more tolerant of people who choose to live according to their own standards,
even if they are very different from our own.”
MBSA7
an ordered factor with levels StronglyDisagree
,
Disagree
, Agree
, and StronglyAgree
, in response to the statement,
“Newer lifestyles are contributing to the breakdown of our society.”
MBSA8
an ordered factor with levels StronglyDisagree
,
Disagree
, Agree
, and StronglyAgree
, in response to the statement,
“The world is always changing and we should adapt our view of moral behaviour to
these changes.”
MBSA9
an ordered factor with levels StronglyDisagree
,
Disagree
, Agree
, and StronglyAgree
, in response to the statement,
“This country would have many fewer problems if there were more emphasis on
traditional family values.”
York University Institute for Social Research.
The sem
method for the standard generic function effects
computes total, direct,
and indirect effects for a fitted structural equation model according to the method described in Fox (1980).
## S3 method for class 'sem' effects(object, ...) ## S3 method for class 'msem' effects(object, ...) ## S3 method for class 'semeffects' print(x, digits = getOption("digits"), ...) ## S3 method for class 'semeffectsList' print(x, digits = getOption("digits"), ...)
## S3 method for class 'sem' effects(object, ...) ## S3 method for class 'msem' effects(object, ...) ## S3 method for class 'semeffects' print(x, digits = getOption("digits"), ...) ## S3 method for class 'semeffectsList' print(x, digits = getOption("digits"), ...)
object |
a fitted structural-equation model object produced by the |
x |
an object of class |
digits |
digits to print. |
... |
not used. |
effect.sem
returns an object of class semeffects
with Total
, Direct
, and Indirect
elements.
John Fox [email protected]
Fox, J. (1980) Effect analysis in structural equation models: Extensions and simplified methods of computation. Sociological Methods and Research 9, 3–28.
## Not run: # These examples are from Fox (1980) # In the first pair of examples, readMoments() and specifyModel() read from the # input stream. These examples cannot be executed via example() but can be entered # at the command prompt. The Blau and Duncan example is repeated using file input; # this example can be executed via example(). # The recursive Blau and Duncan basic stratification model: # x1 is father's education, x2 father's SES, y3 respondent's education, # y4 SES of respondent's first job, y5 respondent's SES in 1962 R.bd <- readMoments(names=c("x1", "x2", "y3", "y4", "y5")) 1 .516 1 .453 .438 1 .332 .417 .538 1 .322 .405 .596 .541 1 mod.bd <- specifyModel() y3 <- x1, gam31 y3 <- x2, gam32 y4 <- x2, gam42 y4 <- y3, beta43 y5 <- x2, gam52 y5 <- y3, beta53 y5 <- y4, beta54 sem.bd <- sem(mod.bd, R.bd, N=20700, fixed.x=c("x1", "x2")) summary(sem.bd) effects(sem.bd) # The nonrecursive Duncan, Haller, and Portes peer-influences model for observed variables: R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RIQ -> ROccAsp, gam51, NA RSES -> ROccAsp, gam52, NA FSES -> FOccAsp, gam63, NA FIQ -> FOccAsp, gam64, NA FOccAsp -> ROccAsp, beta56, NA ROccAsp -> FOccAsp, beta65, NA ROccAsp <-> ROccAsp, ps55, NA FOccAsp <-> FOccAsp, ps66, NA ROccAsp <-> FOccAsp, ps56, NA # Note: The following generates a warning because not all of the variables # in the correlation matrix are used sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RIQ', 'RSES', 'FSES', 'FIQ')) summary(sem.dhp) effects(sem.dhp) ## End(Not run) ## the following example may be executed via example() etc <- system.file(package="sem", "etc") # path to data and model files # The recursive Blau and Duncan basic stratification model: # x1 is father's education, x2 father's SES, y3 respondent's education, # y4 SES of respondent's first job, y5 respondent's SES in 1962 (R.bd <- readMoments(file=file.path(etc, "R-Blau-Duncan.txt"), names=c("x1", "x2", "y3", "y4", "y5"))) (mod.bd <- specifyModel(file=file.path(etc, "model-Blau-Duncan.txt"))) sem.bd <- sem(mod.bd, R.bd, N=20700, fixed.x=c("x1", "x2")) summary(sem.bd) effects(sem.bd)
## Not run: # These examples are from Fox (1980) # In the first pair of examples, readMoments() and specifyModel() read from the # input stream. These examples cannot be executed via example() but can be entered # at the command prompt. The Blau and Duncan example is repeated using file input; # this example can be executed via example(). # The recursive Blau and Duncan basic stratification model: # x1 is father's education, x2 father's SES, y3 respondent's education, # y4 SES of respondent's first job, y5 respondent's SES in 1962 R.bd <- readMoments(names=c("x1", "x2", "y3", "y4", "y5")) 1 .516 1 .453 .438 1 .332 .417 .538 1 .322 .405 .596 .541 1 mod.bd <- specifyModel() y3 <- x1, gam31 y3 <- x2, gam32 y4 <- x2, gam42 y4 <- y3, beta43 y5 <- x2, gam52 y5 <- y3, beta53 y5 <- y4, beta54 sem.bd <- sem(mod.bd, R.bd, N=20700, fixed.x=c("x1", "x2")) summary(sem.bd) effects(sem.bd) # The nonrecursive Duncan, Haller, and Portes peer-influences model for observed variables: R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RIQ -> ROccAsp, gam51, NA RSES -> ROccAsp, gam52, NA FSES -> FOccAsp, gam63, NA FIQ -> FOccAsp, gam64, NA FOccAsp -> ROccAsp, beta56, NA ROccAsp -> FOccAsp, beta65, NA ROccAsp <-> ROccAsp, ps55, NA FOccAsp <-> FOccAsp, ps66, NA ROccAsp <-> FOccAsp, ps56, NA # Note: The following generates a warning because not all of the variables # in the correlation matrix are used sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RIQ', 'RSES', 'FSES', 'FIQ')) summary(sem.dhp) effects(sem.dhp) ## End(Not run) ## the following example may be executed via example() etc <- system.file(package="sem", "etc") # path to data and model files # The recursive Blau and Duncan basic stratification model: # x1 is father's education, x2 father's SES, y3 respondent's education, # y4 SES of respondent's first job, y5 respondent's SES in 1962 (R.bd <- readMoments(file=file.path(etc, "R-Blau-Duncan.txt"), names=c("x1", "x2", "y3", "y4", "y5"))) (mod.bd <- specifyModel(file=file.path(etc, "model-Blau-Duncan.txt"))) sem.bd <- sem(mod.bd, R.bd, N=20700, fixed.x=c("x1", "x2")) summary(sem.bd) effects(sem.bd)
Calculate factor scores or factor-score coefficients for the latent variables in a structural-equation model.
## S3 method for class 'sem' fscores(model, data=model$data, center=TRUE, scale=FALSE, ...) ## S3 method for class 'msem' fscores(model, data=model$data, center=TRUE, scale=FALSE, ...)
## S3 method for class 'sem' fscores(model, data=model$data, center=TRUE, scale=FALSE, ...) ## S3 method for class 'msem' fscores(model, data=model$data, center=TRUE, scale=FALSE, ...)
model |
an object of class |
data |
an optional numeric data frame or matrix containing the observed variables
in the model; if not |
center |
if |
scale |
if |
... |
arguments to pass down. |
Factor-score coefficients are computed by the “regression” method as
, where
is the model-implied covariance or
moment matrix among the observed variables and
is the matrix
of model-implied covariances or moments between the observed and latent variables.
Either a matrix of estimated factor scores (if the data
argument is
supplied) or a matrix of factor-score coefficients (otherwise). In the case of an "msem"
argument, a list of matrices is returned.
John Fox [email protected]
Bollen, K. A. (1989) Structural Equations With Latent Variables. Wiley.
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 # This model in the SAS manual for PROC CALIS model.wh.1 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.1 <- sem(model.wh.1, S.wh, 932) fscores(sem.wh.1) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) (model.wh.1 <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) (sem.wh.1 <- sem(model.wh.1, S.wh, 932)) fscores(sem.wh.1)
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 # This model in the SAS manual for PROC CALIS model.wh.1 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.1 <- sem(model.wh.1, S.wh, 932) fscores(sem.wh.1) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) (model.wh.1 <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) (sem.wh.1 <- sem(model.wh.1, S.wh, 932)) fscores(sem.wh.1)
This data set, for scores on a variety of tests, was originally in the MBESS package. A new version of the data set in that package doesn't appear to be identical to this one.
HS.data
HS.data
A data frame with 301 observations on the following 32 variables.
id
a numeric vector
Gender
a factor with levels Female
Male
grade
a numeric vector
agey
a numeric vector
agem
a numeric vector
school
a factor with levels Grant-White
Pasteur
visual
a numeric vector
cubes
a numeric vector
paper
a numeric vector
flags
a numeric vector
general
a numeric vector
paragrap
a numeric vector
sentence
a numeric vector
wordc
a numeric vector
wordm
a numeric vector
addition
a numeric vector
code
a numeric vector
counting
a numeric vector
straight
a numeric vector
wordr
a numeric vector
numberr
a numeric vector
figurer
a numeric vector
object
a numeric vector
numberf
a numeric vector
figurew
a numeric vector
deduct
a numeric vector
numeric
a numeric vector
problemr
a numeric vector
series
a numeric vector
arithmet
a numeric vector
paperrev
a numeric vector
flagssub
a numeric vector
Originally from Holzinger and Swineford (1939). This copy is originally from version 4.6.0 of the MBESS package.
Holzinger, K. J. and Swineford, F. A. (1939). A study in factor analysis: The stability of a bi-factor solution. Supplementary Education Monographs, 48. University of Chicago.
summary(HS.data)
summary(HS.data)
These are generic functions for computing, respectively, the AICc (second-order corrected Akaike Information Criterion) and CAIC (consistent Akaike Information Criterion).
AICc(object, ...) CAIC(object, ...)
AICc(object, ...) CAIC(object, ...)
object |
an object for which an appropriate |
... |
possible additional arguments for methods. |
Jarrett Byrnes and John Fox [email protected]
Burnham, K. P., and Anderson, D. R. (1998) Model Selection and Inference: A Practical Information-Theoretical Approach. Springer.
Bozdogan, H. (1987) Model selection and Akaike's information criterion (AIC). Psychometrika 52, 345–370.
AICc.objectiveML
, CAIC.objectiveML
Data for Klein's (1950) simple econometric model of the U. S. economy.
The Klein
data frame has 22 rows and 10 columns.
Klein
Klein
This data frame contains the following columns:
1921–1941
consumption.
private profits.
private wages.
investment.
capital stock, lagged one year.
equilibrium demand.
government wages.
government non-wage spending.
indirect business taxes and net exports.
Greene, W. H. (1993) Econometric Analysis, Second Edition. Macmillan.
Klein, L. (1950) Economic Fluctuations in the United States 1921–1941. Wiley.
Klein$P.lag <- c(NA, Klein$P[-22]) Klein$X.lag <- c(NA, Klein$X[-22]) summary(tsls(C ~ P + P.lag + I(Wp + Wg), instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein)) summary(tsls(I ~ P + P.lag + K.lag, instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein)) summary(tsls(Wp ~ X + X.lag + I(Year - 1931), instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein))
Klein$P.lag <- c(NA, Klein$P[-22]) Klein$X.lag <- c(NA, Klein$X[-22]) summary(tsls(C ~ P + P.lag + I(Wp + Wg), instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein)) summary(tsls(I ~ P + P.lag + K.lag, instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein)) summary(tsls(Wp ~ X + X.lag + I(Year - 1931), instruments=~1 + G + T + Wg + I(Year - 1931) + K.lag + P.lag + X.lag, data=Klein))
These are partly contrived data from Kmenta (1986), constructed to illustrate estimation of a simultaneous-equation model.
The Kmenta
data frame has 20 rows and 5 columns.
Kmenta
Kmenta
This data frame contains the following columns:
food consumption per capita.
ratio of food prices to general consumer prices.
disposable income in constant dollars.
ratio of preceding year's prices received by farmers to general consumer prices.
time in years.
The exogenous variables D
, F
, and A
are based on
real data; the endogenous variables P
and Q
were generated
by simulation.
Kmenta, J. (1986) Elements of Econometrics, Second Edition, Macmillan.
miSem
uses the mi
function in the mi package to generate multiple imputations of missing
data, fitting the specified model to each completed data set.
miSem(model, ...) ## S3 method for class 'semmod' miSem(model, ..., data, formula = ~., raw=FALSE, fixed.x=NULL, objective=objectiveML, n.imp=5, n.chains=n.imp, n.iter=30, seed=sample(1e6, 1), mi.args=list(), show.progress=TRUE) ## S3 method for class 'semmodList' miSem(model, ..., data, formula = ~., group, raw=FALSE, fixed.x=NULL, objective=msemObjectiveML, n.imp=5, n.chains=n.imp, n.iter=30, seed=sample(1e6, 1), mi.args=list(), show.progress=TRUE) ## S3 method for class 'miSem' print(x, ...) ## S3 method for class 'miSem' summary(object, digits=max(3, getOption("digits") - 2), ...)
miSem(model, ...) ## S3 method for class 'semmod' miSem(model, ..., data, formula = ~., raw=FALSE, fixed.x=NULL, objective=objectiveML, n.imp=5, n.chains=n.imp, n.iter=30, seed=sample(1e6, 1), mi.args=list(), show.progress=TRUE) ## S3 method for class 'semmodList' miSem(model, ..., data, formula = ~., group, raw=FALSE, fixed.x=NULL, objective=msemObjectiveML, n.imp=5, n.chains=n.imp, n.iter=30, seed=sample(1e6, 1), mi.args=list(), show.progress=TRUE) ## S3 method for class 'miSem' print(x, ...) ## S3 method for class 'miSem' summary(object, digits=max(3, getOption("digits") - 2), ...)
model |
an SEM model-description object of class |
... , formula , raw , fixed.x , objective , group
|
arguments to be passed to |
data |
an R data frame, presumably with some missing data (encoded as |
n.imp |
number of imputations (default |
n.chains |
number of Markov chains (default is the number of imputations). |
n.iter |
number of iterations for the multiple-imputation process (default |
seed |
seed for the random-number generator (default is an integer sampled from 1 to 1E6); stored in the resulting object. |
mi.args |
other arguments to be passed to |
show.progress |
show a text progress bar on the console tracking model fitting to the multiple imputations; this is distinct from
the progress of the multiple-imputation process, which is controlled by the |
x , object
|
an object of class |
digits |
for printing numbers. |
miSem
returns an object of class "miSem"
with the following components:
initial.fit |
an |
mi.fits |
a list of |
imputation |
the object produced by |
seed |
the seed used for the random number generator. |
mi.data |
the object returned by |
John Fox [email protected]
Yu-Sung Su, Andrew Gelman, Jennifer Hill, Masanao Yajima. (2011). “Multiple imputation with diagnostics (mi) in R: Opening windows into the black box.” Journal of Statistical Software 45(2).
## Not run: # because of long execution time mod.cfa.tests <- cfa(raw=TRUE, text=" verbal: x1, x2, x3 math: y1, y2, y3 ") imps <- miSem(mod.cfa.tests, data=Tests, fixed.x="Intercept", raw=TRUE, seed=12345) summary(imps, digits=3) # introduce some missing data to the HS.data data set: HS <- HS.data[, c(2,7:10,11:15,20:25,26:30)] set.seed(12345) r <- sample(301, 100, replace=TRUE) c <- sample(2:21, 100, replace=TRUE) for (i in 1:100) HS[r[i], c[i]] <- NA mod.hs <- cfa(text=" spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet ") mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) system.time( # relatively time-consuming! imps.mg <- miSem(mod.mg, data=HS, group="Gender", seed=12345) ) summary(imps.mg, digits=3) ## End(Not run)
## Not run: # because of long execution time mod.cfa.tests <- cfa(raw=TRUE, text=" verbal: x1, x2, x3 math: y1, y2, y3 ") imps <- miSem(mod.cfa.tests, data=Tests, fixed.x="Intercept", raw=TRUE, seed=12345) summary(imps, digits=3) # introduce some missing data to the HS.data data set: HS <- HS.data[, c(2,7:10,11:15,20:25,26:30)] set.seed(12345) r <- sample(301, 100, replace=TRUE) c <- sample(2:21, 100, replace=TRUE) for (i in 1:100) HS[r[i], c[i]] <- NA mod.hs <- cfa(text=" spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet ") mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) system.time( # relatively time-consuming! imps.mg <- miSem(mod.mg, data=HS, group="Gender", seed=12345) ) summary(imps.mg, digits=3) ## End(Not run)
objectiveML
, objectiveGLS
, objectiveFIML
, msemObjectiveML
,
and msemObjectiveGLS
Objective Functions
These functions are for objects fit by sem
using the objectiveML
(multivariate-normal full-information maximum-likelihood), link{objectiveFIML}
(multivariate-normal full-information maximum-likihood in
the presence of missing data),
objectiveGLS
(generalized least squares), and msemObjectiveML
(multigroup multivariate-normal FIML) objective functions.
## S3 method for class 'objectiveML' anova(object, model.2, robust=FALSE, ...) ## S3 method for class 'objectiveFIML' anova(object, model.2, ...) ## S3 method for class 'objectiveML' logLik(object, ...) ## S3 method for class 'objectiveFIML' logLik(object, saturated=FALSE, intercept="Intercept", iterlim=1000, ...) ## S3 method for class 'objectiveML' deviance(object, ...) ## S3 method for class 'objectiveFIML' deviance(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' deviance(object, ...) ## S3 method for class 'objectiveML' AIC(object, ..., k) ## S3 method for class 'objectiveFIML' AIC(object, saturated.logLik, ..., k) ## S3 method for class 'msemObjectiveML' AIC(object, ..., k) ## S3 method for class 'objectiveML' AICc(object, ...) ## S3 method for class 'objectiveFIML' AICc(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' AICc(object, ...) ## S3 method for class 'objectiveML' BIC(object, ...) ## S3 method for class 'objectiveFIML' BIC(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' BIC(object, ...) ## S3 method for class 'objectiveML' CAIC(object, ...) ## S3 method for class 'objectiveFIML' CAIC(object, saturated.logLik, ...) ## S3 method for class 'objectiveML' print(x, ...) ## S3 method for class 'objectiveGLS' print(x, ...) ## S3 method for class 'objectiveFIML' print(x, saturated=FALSE, ...) ## S3 method for class 'msemObjectiveML' print(x, ...) ## S3 method for class 'msemObjectiveGLS' print(x, ...) ## S3 method for class 'objectiveML' summary(object, digits=getOption("digits"), conf.level=.90, robust=FALSE, analytic.se=object$t <= 500, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC", "CAIC"), ...) ## S3 method for class 'objectiveFIML' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("AIC", "AICc", "BIC", "CAIC"), saturated=FALSE, intercept="Intercept", saturated.logLik, ...) ## S3 method for class 'objectiveGLS' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR"), ...) ## S3 method for class 'msemObjectiveML' summary(object, digits=getOption("digits"), conf.level=.90, robust=FALSE, analytic.se=object$t <= 500, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC"), ...) ## S3 method for class 'msemObjectiveGLS' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR"), ...)
## S3 method for class 'objectiveML' anova(object, model.2, robust=FALSE, ...) ## S3 method for class 'objectiveFIML' anova(object, model.2, ...) ## S3 method for class 'objectiveML' logLik(object, ...) ## S3 method for class 'objectiveFIML' logLik(object, saturated=FALSE, intercept="Intercept", iterlim=1000, ...) ## S3 method for class 'objectiveML' deviance(object, ...) ## S3 method for class 'objectiveFIML' deviance(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' deviance(object, ...) ## S3 method for class 'objectiveML' AIC(object, ..., k) ## S3 method for class 'objectiveFIML' AIC(object, saturated.logLik, ..., k) ## S3 method for class 'msemObjectiveML' AIC(object, ..., k) ## S3 method for class 'objectiveML' AICc(object, ...) ## S3 method for class 'objectiveFIML' AICc(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' AICc(object, ...) ## S3 method for class 'objectiveML' BIC(object, ...) ## S3 method for class 'objectiveFIML' BIC(object, saturated.logLik, ...) ## S3 method for class 'msemObjectiveML' BIC(object, ...) ## S3 method for class 'objectiveML' CAIC(object, ...) ## S3 method for class 'objectiveFIML' CAIC(object, saturated.logLik, ...) ## S3 method for class 'objectiveML' print(x, ...) ## S3 method for class 'objectiveGLS' print(x, ...) ## S3 method for class 'objectiveFIML' print(x, saturated=FALSE, ...) ## S3 method for class 'msemObjectiveML' print(x, ...) ## S3 method for class 'msemObjectiveGLS' print(x, ...) ## S3 method for class 'objectiveML' summary(object, digits=getOption("digits"), conf.level=.90, robust=FALSE, analytic.se=object$t <= 500, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC", "CAIC"), ...) ## S3 method for class 'objectiveFIML' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("AIC", "AICc", "BIC", "CAIC"), saturated=FALSE, intercept="Intercept", saturated.logLik, ...) ## S3 method for class 'objectiveGLS' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR"), ...) ## S3 method for class 'msemObjectiveML' summary(object, digits=getOption("digits"), conf.level=.90, robust=FALSE, analytic.se=object$t <= 500, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC"), ...) ## S3 method for class 'msemObjectiveGLS' summary(object, digits=getOption("digits"), conf.level=.90, fit.indices=c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR"), ...)
object , model.2 , x
|
an object inheriting from class |
robust |
if |
fit.indices |
a character vector of “fit indices” to report; the allowable values are those given in Usage
above, and vary by the objective function. If the argument isn't given then the fit indices reported are taken
from the R |
k , ...
|
ignored. |
digits |
digits to be printed. |
conf.level |
level for confidence interval for the RMSEA index (default is .9). |
analytic.se |
use analytic (as opposed to numeric) coefficient standard errors; default is |
saturated |
if |
intercept |
the name of the intercept regressor in the raw data, to be used in calculating the
saturated log-likelihood for the FIML estimator; the default is |
saturated.logLik |
the log-likelihood for the saturated model, as returned by |
iterlim |
iteration limit used by the |
John Fox [email protected] and Jarrett Byrnes
See sem
.
sem
, objective.functions
, modIndices.objectiveML
mod.indices
calculates modification indices (score tests)
and estimated parameter changes for the fixed and constrained
parameters in a structural equation model fit by multinormal maximum likelihood.
## S3 method for class 'objectiveML' modIndices(model, duplicated, deviance=NULL, ...) ## S3 method for class 'msemObjectiveML' modIndices(model, ...) ## S3 method for class 'modIndices' print(x, n.largest=5, ...) ## S3 method for class 'msemModIndices' print(x, ...) ## S3 method for class 'modIndices' summary(object, round=2, print.matrices=c("both", "par.change", "mod.indices"), ...) ## S3 method for class 'msemModIndices' summary(object, ...)
## S3 method for class 'objectiveML' modIndices(model, duplicated, deviance=NULL, ...) ## S3 method for class 'msemObjectiveML' modIndices(model, ...) ## S3 method for class 'modIndices' print(x, n.largest=5, ...) ## S3 method for class 'msemModIndices' print(x, ...) ## S3 method for class 'modIndices' summary(object, round=2, print.matrices=c("both", "par.change", "mod.indices"), ...) ## S3 method for class 'msemModIndices' summary(object, ...)
model |
an object of class |
object , x
|
an object of class |
n.largest |
number of modification indices to print in each of the |
round |
number of places to the right of the decimal point in printing modification indices. |
print.matrices |
which matrices to print: estimated changes in the fixed parameters, modification indices, or both (the default). |
duplicated , deviance
|
for internal use. |
... |
arguments to be passed down. |
Modification indices are one-df chi-square score (“Lagrange-multiplier”) test statistics for the fixed and constrained
parameters in a structural equation model. They may be regarded as an estimate of the improvement
in the likelihood-ratio chi-square statistic for the model if the corresponding parameter is
respecified as a free parameter. The modIndices
function also estimates the change in the
value of a fixed or constrained parameter if the parameter is respecified as free. When several
parameters are set equal, modification indices and estimated changes are given for all but the first.
Modification indices and estimated parameter changes for currently free parameters are given as
NA
.
The method employed is described in Saris, Satorra, and Sorbom (1987) and Sorbom (1989).
modIndices
returns an object of class modIndices
with the following elements:
mod.A |
modification indices for the elements of the |
mod.P |
modification indices for the elements of the |
par.A |
estimated parameter changes for the elements of the |
par.P |
estimated parameter changes for the elements of the |
John Fox [email protected] and Michael Culbertson
Sarris, W. E., Satorra, A., and Sorbom, D. (1987) The detection and correction of specification errors in structural equation models. Pp. 105–129 in Clogg, C. C. (ed.), Sociological Methodology 1987. American Sociological Association.
Sorbom, D. (1989) Model modification. Psychometrika 54, 371–384.
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # This example is adapted from the SAS manual S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 model.wh <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh <- sem(model.wh, S.wh, 932) modIndices(sem.wh) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) (model.wh <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) (sem.wh <- sem(model.wh, S.wh, 932)) modIndices(sem.wh)
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # This example is adapted from the SAS manual S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 model.wh <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh <- sem(model.wh, S.wh, 932) modIndices(sem.wh) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) (model.wh <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) (sem.wh <- sem(model.wh, S.wh, 932)) modIndices(sem.wh)
These functions return objective functions suitable for use with optimizers
called by sem
. The user would not
normally call these functions directly, but rather supply one of them in the objective
argument to
sem
. Users may also write their own objective functions. objectiveML
and objectiveML2
are for multinormal maximum-likelihood
estimation; objectiveGLS
and objectiveGLS2
are for generalized least squares; and objectiveFIML2
is for so-called “full-information maximum-likelihood” estimation in the presence of missing data. The FIML estimator
provides the same estimates as the ML estimator when there is no missing data; it can be slow because it iterates over
the unique patterns of missing data that occur in the data set.
objectiveML
and objectiveGLS
use
compiled code and are therefore substantially faster. objectiveML2
and objectiveGLS2
are provided primarily to illustrate
how to write sem
objective functions in R. msemObjectiveML
uses compiled code is for fitting multi-group models by
multinormal maximum likelihood; msemObjectiveML2
is similar but doesn't use compiled code. msemObjectiveGLS
uses compiled
code and is for fitting multi-group models by generalized least squares.
objectiveML(gradient=TRUE, hessian=FALSE) objectiveML2(gradient=TRUE) objectiveGLS(gradient=FALSE) objectiveGLS2(gradient=FALSE) objectiveFIML(gradient=TRUE, hessian=FALSE) objectiveFIML2(gradient=TRUE, hessian=FALSE) msemObjectiveML(gradient=TRUE) msemObjectiveML2(gradient=TRUE) msemObjectiveGLS(gradient=FALSE)
objectiveML(gradient=TRUE, hessian=FALSE) objectiveML2(gradient=TRUE) objectiveGLS(gradient=FALSE) objectiveGLS2(gradient=FALSE) objectiveFIML(gradient=TRUE, hessian=FALSE) objectiveFIML2(gradient=TRUE, hessian=FALSE) msemObjectiveML(gradient=TRUE) msemObjectiveML2(gradient=TRUE) msemObjectiveGLS(gradient=FALSE)
gradient |
If |
hessian |
If |
These functions return an object of class "semObjective"
, with up to two elements:
objective |
an objective function. |
gradient |
a gradient function. |
John Fox [email protected]
See sem
.
The default optimizer used by sem
is optimizerSem
, which employs compiled code and is integrated with
the objectiveML
and objectiveGLS
objective functions;
optimizerSem
, written by Zhenghua Nie, is a modified
version of the standard R nlm
optimizer, which was written by Saikat DebRoy, R-core, and Richard H. Jones.
The other functions call optimizers (nlm
, optim
, or nlminb
),
to fit structural equation models, and are called by the sem
function.
The user would not normally call these functions directly, but rather supply one of them in the optimizer
argument to
sem
. Users may also write them own optimizer functions. msemOptimizerNlm
is for fitting multigroup models, and also adapts the nlm
code.
optimizerSem(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) optimizerMsem(start, objective=msemObjectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn=FALSE, ...) optimizerNlm(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) optimizerOptim(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, method="CG", ...) optimizerNlminb(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) msemOptimizerNlm(start, objective=msemObjectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn=FALSE, ...)
optimizerSem(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) optimizerMsem(start, objective=msemObjectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn=FALSE, ...) optimizerNlm(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) optimizerOptim(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, method="CG", ...) optimizerNlminb(start, objective=objectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn, ...) msemOptimizerNlm(start, objective=msemObjectiveML, gradient=TRUE, maxiter, debug, par.size, model.description, warn=FALSE, ...)
start |
a vector of start values for the parameters. |
objective |
the objective function to be optimized; see objective.functions. |
gradient |
|
maxiter |
the maximum number of iterations allowed. |
debug |
|
par.size |
|
model.description |
a list with elements describing the structural-equation model (see the code for details). |
warn |
if |
method |
the method to be employed by the |
... |
additional arguments for the |
An object of class "semResult"
, with elements:
convergence |
|
iterations |
the number of iterations required. |
par |
the vector of parameter estimates. |
vcov |
the estimated covariance matrix of the parameter estimates, based on a numeric Hessian; not supplied by |
criterion |
the optimized value of the objective function. |
C |
the model-implied covariance or moment matrix at the parameter estimates. |
A |
the estimated |
P |
the estimated |
John Fox [email protected], and Zhenghua Nie, in part adapting work by Saikat DebRoy, R-core, and Richard H. Jones.
sem
, objective.functions
, nlm
, optim
, nlminb
pathDiagram
creates a description of the path diagram
for a structural-equation-model or SEM-specification object to be processed by the
graph-drawing program dot.
pathDiagram(model, ...) ## S3 method for class 'sem' pathDiagram(model, file = "pathDiagram", style = c("ram", "traditional"), output.type = c("html", "graphics", "dot"), graphics.fmt = "pdf", dot.options = NULL, size = c(8, 8), node.font = c("Helvetica", 14), edge.font = c("Helvetica", 10), digits = 2, rank.direction = c("LR", "TB"), min.rank = NULL, max.rank = NULL, same.rank = NULL, variables = model$var.names, var.labels, parameters, par.labels, ignore.double = TRUE, ignore.self = FALSE, error.nodes = TRUE, edge.labels = c("names", "values", "both"), edge.colors = c("black", "black"), edge.weight = c("fixed", "proportional"), node.colors = c("transparent", "transparent", "transparent"), standardize = FALSE, ...) ## S3 method for class 'semmod' pathDiagram(model, obs.variables, ...) math(text, html.only=FALSE, hat=FALSE)
pathDiagram(model, ...) ## S3 method for class 'sem' pathDiagram(model, file = "pathDiagram", style = c("ram", "traditional"), output.type = c("html", "graphics", "dot"), graphics.fmt = "pdf", dot.options = NULL, size = c(8, 8), node.font = c("Helvetica", 14), edge.font = c("Helvetica", 10), digits = 2, rank.direction = c("LR", "TB"), min.rank = NULL, max.rank = NULL, same.rank = NULL, variables = model$var.names, var.labels, parameters, par.labels, ignore.double = TRUE, ignore.self = FALSE, error.nodes = TRUE, edge.labels = c("names", "values", "both"), edge.colors = c("black", "black"), edge.weight = c("fixed", "proportional"), node.colors = c("transparent", "transparent", "transparent"), standardize = FALSE, ...) ## S3 method for class 'semmod' pathDiagram(model, obs.variables, ...) math(text, html.only=FALSE, hat=FALSE)
model |
a structural-equation-model or SEM-specification object produced by |
... |
arguments passed down, e.g., from the |
file |
a file name, by default |
style |
|
output.type |
if |
graphics.fmt |
a graphics format recognized by the dot program; the default is |
dot.options |
options to be passed to the dot program, given as a character string. |
size |
the size of the graph, in inches. |
node.font |
font name and point-size for printing variable names. |
edge.font |
font name and point-size for printing arrow names or values. |
digits |
number of digits after the decimal point (default, 2) to which to round parameter estimates. |
rank.direction |
draw graph left-to-right, |
min.rank |
a character string listing names of variables to be assigned minimum rank (order) in the graph; the names should be separated by commas. |
max.rank |
a character string listing names of variables to be assigned maximum rank in the graph; the names should be separated by commas. |
same.rank |
a character string or vector of character strings of variables to be assigned equivalent rank in the graph; names in each string should be separated by commas. |
variables |
variable names; defaults to the variable names in |
var.labels |
a character vector with labels to be used
in lieu of (some of) the variables names, for greater flexibility
in labelling nodes in the graph — e.g., the labels can be created with the |
parameters |
parameter names; defaults to the parameter names in
|
par.labels |
a character vector with labels to be used
in lieu of (some of) the parameter names, for greater flexibility
in labelling edges in the graph — e.g., the labels can be created with the |
ignore.double |
if |
ignore.self |
if |
error.nodes |
if |
edge.labels |
|
edge.colors |
two-element character vector giving colors of positive
and negative arrows respectively; the default is |
edge.weight |
if |
node.colors |
a two- or three-element character vector giving colors of nodes representing
exogenous, endogenous, and error variables (for traditional path diagrams) consecutively;
the default is |
standardize |
if |
obs.variables |
a character vector with the names of the observed variables in the model. |
text |
a character string or vector of character strings to be translated into node or edge label symbols. If a vector of character strings is supplied, then the elements of the vector should be named with the corresponding variable (node) or parameter (edge) name. |
html.only |
If |
hat |
If |
pathDiagram
creates a description of the path diagram
for a structural-equation-model or SEM-specification object to be processed by the
graph-drawing program dot, which can be called
automatically; see Koutsofios and North (2002)
and https://www.graphviz.org/. To obtain graphics output
directly, the dot program must be on the system search path.
Alternatively, HTML output can be created in a web browser without an independent installation
of dot
using facilities in the DiagrammeR package.
The math
function can be used to create node (variable) and edge (arrow) labels with
symbols such as Greek letters, subscripts, and superscripts.
The semmod
method of pathDiagram
sets up a call to the sem
method.
The various
arguments to pathDiagram
can be used to customize the diagram, but if there are too many constraints
on node placement, dot may fail to produce a graph or may produce a distorted graph.
pathDiagram
can create both RAM-style diagrams, in which variances are represented as self-directed
arrows, and traditional path diagrams, in which error variables appear explicitly as nodes. As is conventional,
latent variables (including error variables) are represented as ellipses and observed variables as
rectangles; double-headed arrows represent covariances (and in RAM diagrams, variances) and single-headed
arrows represent structural coefficients.
pathDiagram
invisibly returns a character vector containing dot commands.
math
returns a character vector containing suitable HTML
markup.
John Fox [email protected], Adam Kramer, and Michael Friendly
Koutsofios, E., and North, S. C. (2002) Drawing graphs with dot. https://graphviz.org/documentation/.
sem
, specifyEquations
, specifyModel
, cfa
if (interactive()) { # The Duncan, Haller, and Portes Peer-Influences Model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") model.dhp <- specifyModel(text=" RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA ") sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c("RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) pathDiagram(sem.dhp, min.rank="RIQ, RSES, RParAsp, FParAsp, FSES, FIQ", max.rank="ROccAsp, REdAsp, FEdAsp, FOccAsp", same.rank="RGenAsp, FGenAsp", edge.labels="values") pathDiagram(model.dhp, obs.variables=c("RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp", "ROccAsp", "REdAsp", "FOccAsp", "FEdAsp"), style="traditional", node.colors=c("pink", "lightblue", "lightgreen"), min.rank="RIQ, RSES, RParAsp, FParAsp, FSES, FIQ", max.rank="ROccAsp, REdAsp, FEdAsp, FOccAsp", same.rank="RGenAsp, FGenAsp", var.labels=c(RParAsp="Respondent Parental Aspiration", RIQ="Respondent IQ", RSES="Respondent SES", FSES="Friend SES", FIQ="Friend IQ", FParAsp="Friend Parental Aspiration", ROccAsp="Respondent Occupational Aspiration", REdAsp="Respondent Educational Aspiration", RGenAsp="Respondent General Aspiration", FOccAsp="Friend Occupational Aspiration", FEdAsp="Friend Educational Aspiration", FGenAsp="Friend General Aspiration", math(c(RGenAsp.error="xi_{1}", FGenAsp.error="xi_{2}", ROccAsp.error="epsilon_{1}", REdAsp.error="epsilon_{2}", FOccAsp.error="epsilon_{3}", FEdAsp.error="epsilon_{4}"))), par.labels=math(c(gam11="gamma_{11}", gam12="gamma_{12}", gam13="gamma_{13}", gam14="gamma_{14}", gam23="gamma_{23}", gam24="gamma_{24}", gam25="gamma_{25}", gam26="gamma_{26}", beta12="beta_{12}", beta21="beta_{21}", lam21="lambda_{21}", lam42="lambda_{42}", ps11="psi_{11}", ps22="psi_{22}", ps12="psi_{12}", theta1="theta_{1}", theta2="theta_{2}", theta3="theta_{3}", theta4="theta_{4}"))) # the following example contributed by Michael Friendly: union <- readMoments(diag=TRUE, names=c('y1', 'y2', 'y3', 'x1', 'x2'), text=" 14.610 -5.250 11.017 -8.057 11.087 31.971 -0.482 0.677 1.559 1.021 -18.857 17.861 28.250 7.139 215.662 ") union.mod <- specifyEquations(covs=c("x1, x2"), text=" y1 = gam12*x2 y2 = beta21*y1 + gam22*x2 y3 = beta31*y1 + beta32*y2 + gam31*x1 ") union.sem <- sem(union.mod, union, N=173) dot <- pathDiagram(union.sem, style="traditional", ignore.double=FALSE, error.nodes=FALSE, edge.labels="values", min.rank=c("Years", "Age"), max.rank=c("Sentiment", "Sentiment.error"), same.rank=c("Deference, Deference.error", "Activism, Activism.error"), variables=c("Deference", "Activism", "Sentiment", "Years", "Age"), edge.colors=c("black", "red"), node.colors = c("pink", "lightblue")) cat(paste(dot, collapse="\n")) # dot commands }
if (interactive()) { # The Duncan, Haller, and Portes Peer-Influences Model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") model.dhp <- specifyModel(text=" RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA ") sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c("RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) pathDiagram(sem.dhp, min.rank="RIQ, RSES, RParAsp, FParAsp, FSES, FIQ", max.rank="ROccAsp, REdAsp, FEdAsp, FOccAsp", same.rank="RGenAsp, FGenAsp", edge.labels="values") pathDiagram(model.dhp, obs.variables=c("RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp", "ROccAsp", "REdAsp", "FOccAsp", "FEdAsp"), style="traditional", node.colors=c("pink", "lightblue", "lightgreen"), min.rank="RIQ, RSES, RParAsp, FParAsp, FSES, FIQ", max.rank="ROccAsp, REdAsp, FEdAsp, FOccAsp", same.rank="RGenAsp, FGenAsp", var.labels=c(RParAsp="Respondent Parental Aspiration", RIQ="Respondent IQ", RSES="Respondent SES", FSES="Friend SES", FIQ="Friend IQ", FParAsp="Friend Parental Aspiration", ROccAsp="Respondent Occupational Aspiration", REdAsp="Respondent Educational Aspiration", RGenAsp="Respondent General Aspiration", FOccAsp="Friend Occupational Aspiration", FEdAsp="Friend Educational Aspiration", FGenAsp="Friend General Aspiration", math(c(RGenAsp.error="xi_{1}", FGenAsp.error="xi_{2}", ROccAsp.error="epsilon_{1}", REdAsp.error="epsilon_{2}", FOccAsp.error="epsilon_{3}", FEdAsp.error="epsilon_{4}"))), par.labels=math(c(gam11="gamma_{11}", gam12="gamma_{12}", gam13="gamma_{13}", gam14="gamma_{14}", gam23="gamma_{23}", gam24="gamma_{24}", gam25="gamma_{25}", gam26="gamma_{26}", beta12="beta_{12}", beta21="beta_{21}", lam21="lambda_{21}", lam42="lambda_{42}", ps11="psi_{11}", ps22="psi_{22}", ps12="psi_{12}", theta1="theta_{1}", theta2="theta_{2}", theta3="theta_{3}", theta4="theta_{4}"))) # the following example contributed by Michael Friendly: union <- readMoments(diag=TRUE, names=c('y1', 'y2', 'y3', 'x1', 'x2'), text=" 14.610 -5.250 11.017 -8.057 11.087 31.971 -0.482 0.677 1.559 1.021 -18.857 17.861 28.250 7.139 215.662 ") union.mod <- specifyEquations(covs=c("x1, x2"), text=" y1 = gam12*x2 y2 = beta21*y1 + gam22*x2 y3 = beta31*y1 + beta32*y2 + gam31*x1 ") union.sem <- sem(union.mod, union, N=173) dot <- pathDiagram(union.sem, style="traditional", ignore.double=FALSE, error.nodes=FALSE, edge.labels="values", min.rank=c("Years", "Age"), max.rank=c("Sentiment", "Sentiment.error"), same.rank=c("Deference, Deference.error", "Activism, Activism.error"), variables=c("Deference", "Activism", "Sentiment", "Years", "Age"), edge.colors=c("black", "red"), node.colors = c("pink", "lightblue")) cat(paste(dot, collapse="\n")) # dot commands }
Print the labelled RAM definition matrix for a structural-equation
model fit by sem
.
ram(object, digits=getOption("digits"), startvalues=FALSE)
ram(object, digits=getOption("digits"), startvalues=FALSE)
object |
an object of class |
digits |
number of digits for printed output. |
startvalues |
if |
A data frame containing the labelled RAM definition matrix, which is normally just printed.
John Fox [email protected]
# ------------- assumes that Duncan, Haller and Portes peer-influences model # ------------- has been fit and is in sem.dhp ## Not run: ram(sem.dhp) ## End(Not run)
# ------------- assumes that Duncan, Haller and Portes peer-influences model # ------------- has been fit and is in sem.dhp ## Not run: ram(sem.dhp) ## End(Not run)
Computes the “uncorrected” sum-of-squares-and-products matrix divided by the number of observations.
## S3 method for class 'formula' rawMoments(formula, data, subset, na.action, contrasts=NULL, ...) ## Default S3 method: rawMoments(object, na.rm=FALSE, ...) cov2raw(cov, mean, N, sd) ## S3 method for class 'rawmoments' print(x, ...)
## S3 method for class 'formula' rawMoments(formula, data, subset, na.action, contrasts=NULL, ...) ## Default S3 method: rawMoments(object, na.rm=FALSE, ...) cov2raw(cov, mean, N, sd) ## S3 method for class 'rawmoments' print(x, ...)
object |
a one-sided model formula or an object coercible to a numeric matrix. |
formula |
a one-sided model formula specifying the model matrix for
which raw moments are to be computed; note that a constant is included
if it is not explicitly suppressed by putting |
data |
an optional data frame containing the variables in the formula.
By default the variables are taken from the environment from which
|
subset |
an optional vector specifying a subset of observations to be used in computing moments. |
na.action |
a function that indicates what should happen when the data
contain |
contrasts |
an optional list. See the |
.
na.rm |
if |
cov |
a covariance or correlation matrix. |
mean |
a vector of means. |
N |
the number of observations on which the covariances or correlations are based. |
sd |
an optional vector of standard deviations, to be given if |
x |
an object of class |
... |
arguments passed down. |
rawMoments
and cov2raw
return an object of class rawmoments
,
which is simply a matrix
with an attribute "N"
that contains the number of observations on
which the moments are based.
John Fox [email protected]
# the following are all equivalent (with the exception of the name of the intercept): rawMoments(cbind(1, Kmenta)) rawMoments(~ Q + P + D + F + A, data=Kmenta) Cov <- with(Kmenta, cov(cbind(Q, P, D, F, A))) cov2raw(Cov, colMeans(Kmenta), nrow(Kmenta))
# the following are all equivalent (with the exception of the name of the intercept): rawMoments(cbind(1, Kmenta)) rawMoments(~ Q + P + D + F + A, data=Kmenta) Cov <- with(Kmenta, cov(cbind(Q, P, D, F, A))) cov2raw(Cov, colMeans(Kmenta), nrow(Kmenta))
This functions makes it simpler to input covariance, correlation, and raw-moment
matrices to be analyzed by the sem
function. The matrix
is input in lower-triangular form on as many lines as is convenient,
omitting the above-diagonal elements. The
elements on the diagonal may also optionally be omitted, in which case they
are taken to be 1.
readMoments(file="", text, diag=TRUE, names=as.character(paste("X", 1:n, sep = "")))
readMoments(file="", text, diag=TRUE, names=as.character(paste("X", 1:n, sep = "")))
file |
The (quoted) file from which to read the moment matrix,
including the path to the file if it is not in the current directory. If
|
text |
The moment matrix given as a character string, as an alternative
to specifying the |
diag |
If |
names |
a character vector containing the names of the variables, to label the rows and columns of the moment matrix. |
Returns a lower-triangular matrix (i.e., with zeroes above the main diagonal)
suitable for input to sem
.
John Fox [email protected]
R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") R.DHP #the following will work only in an interactive sessions: ## Not run: R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 R.DHP ## End(Not run)
R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") R.DHP #the following will work only in an interactive sessions: ## Not run: R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 R.DHP ## End(Not run)
These functions compute residual covariances, variance-standardized
residual covariances, and normalized residual covariances
for the observed variables in a structural-equation
model fit by sem
.
## S3 method for class 'sem' residuals(object, ...) ## S3 method for class 'msem' residuals(object, ...) ## S3 method for class 'sem' standardizedResiduals(object, ...) ## S3 method for class 'msem' standardizedResiduals(object, ...) ## S3 method for class 'objectiveML' normalizedResiduals(object, ...) ## S3 method for class 'objectiveGLS' normalizedResiduals(object, ...) ## S3 method for class 'msemObjectiveML' normalizedResiduals(object, ...)
## S3 method for class 'sem' residuals(object, ...) ## S3 method for class 'msem' residuals(object, ...) ## S3 method for class 'sem' standardizedResiduals(object, ...) ## S3 method for class 'msem' standardizedResiduals(object, ...) ## S3 method for class 'objectiveML' normalizedResiduals(object, ...) ## S3 method for class 'objectiveGLS' normalizedResiduals(object, ...) ## S3 method for class 'msemObjectiveML' normalizedResiduals(object, ...)
object |
an object inheriting from class |
... |
not for the user. |
Residuals are defined as , where
is the sample covariance matrix
of the observed variables and
is the model-reproduced covariance matrix.
The standardized residual covariance for a pair of variables divides the
residual covariance by the product of the sample standard deviations of the
two variables,
. The normalized residual
is given by
where is the number of observations minus one if the model is fit to a
covariance matrix, or the number of observations if it is fit to a raw moment matrix.
Each function returns a matrix of residuals.
John Fox [email protected]
Bollen, K. A. (1989) Structural Equations With Latent Variables. Wiley.
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # Duncan, Haller, and Portes peer-influences model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) residuals(sem.dhp) normalizedResiduals(sem.dhp) standardizedResiduals(sem.dhp) # same as residuals because model is fit to correlations ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) (sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp'))) residuals(sem.dhp) normalizedResiduals(sem.dhp) standardizedResiduals(sem.dhp) # same as residuals because model is fit to correlations
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # Duncan, Haller, and Portes peer-influences model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) residuals(sem.dhp) normalizedResiduals(sem.dhp) standardizedResiduals(sem.dhp) # same as residuals because model is fit to correlations ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) (sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp'))) residuals(sem.dhp) normalizedResiduals(sem.dhp) standardizedResiduals(sem.dhp) # same as residuals because model is fit to correlations
sem
fits general structural equation models (with both observed and
unobserved variables). Observed variables are also called indicators or
manifest variables; unobserved variables are also called factors
or latent variables. Normally, the generic function (sem
) is
called directly with a semmod
first argument produced by specifyModel
,
specifyEquations
, or cfa
, invoking the sem.semmod
method, which in turn sets up a call to the sem.default
method; thus, the user
may wish to specify arguments accepted by the semmod
and default
methods.
Similarly, for a multigroup model, sem
would normally be called with a
semmodList
object produced by multigroupModel
as its first argument,
and would then generate a call to the code msemmod
method.
## S3 method for class 'semmod' sem(model, S, N, data, raw=identical(na.action, na.pass), obs.variables=rownames(S), fixed.x=NULL, formula= ~ ., na.action=na.omit, robust=!missing(data), debug=FALSE, optimizer=optimizerSem, objective=objectiveML, ...) ## Default S3 method: sem(model, S, N, raw=FALSE, data=NULL, start.fn=startvalues, pattern.number=NULL, valid.data.patterns=NULL, use.means=TRUE, param.names, var.names, fixed.x=NULL, robust=!is.null(data), semmod=NULL, debug=FALSE, analytic.gradient=!identical(objective, objectiveFIML), warn=FALSE, maxiter=1000, par.size=c("ones", "startvalues"), start.tol=1E-6, optimizer=optimizerSem, objective=objectiveML, cls, ...) ## S3 method for class 'semmodList' sem(model, S, N, data, raw=FALSE, fixed.x=NULL, robust=!missing(data), formula, group="Group", debug=FALSE, ...) ## S3 method for class 'msemmod' sem(model, S, N, start.fn=startvalues, group="Group", groups=names(model), raw=FALSE, fixed.x, param.names, var.names, debug=FALSE, analytic.gradient=TRUE, warn=FALSE, maxiter=5000, par.size = c("ones", "startvalues"), start.tol = 1e-06, start=c("initial.fit", "startvalues"), initial.maxiter=1000, optimizer = optimizerMsem, objective = msemObjectiveML, ...) startvalues(S, ram, debug=FALSE, tol=1E-6) startvalues2(S, ram, debug=FALSE, tol=1E-6) ## S3 method for class 'sem' coef(object, standardized=FALSE, ...) ## S3 method for class 'msem' coef(object, ...) ## S3 method for class 'sem' vcov(object, robust=FALSE, analytic=inherits(object, "objectiveML") && object$t <= 500, ...) ## S3 method for class 'msem' vcov(object, robust=FALSE, analytic=inherits(object, "msemObjectiveML") && object$t <= 500, ...) ## S3 method for class 'sem' df.residual(object, ...) ## S3 method for class 'msem' df.residual(object, ...)
## S3 method for class 'semmod' sem(model, S, N, data, raw=identical(na.action, na.pass), obs.variables=rownames(S), fixed.x=NULL, formula= ~ ., na.action=na.omit, robust=!missing(data), debug=FALSE, optimizer=optimizerSem, objective=objectiveML, ...) ## Default S3 method: sem(model, S, N, raw=FALSE, data=NULL, start.fn=startvalues, pattern.number=NULL, valid.data.patterns=NULL, use.means=TRUE, param.names, var.names, fixed.x=NULL, robust=!is.null(data), semmod=NULL, debug=FALSE, analytic.gradient=!identical(objective, objectiveFIML), warn=FALSE, maxiter=1000, par.size=c("ones", "startvalues"), start.tol=1E-6, optimizer=optimizerSem, objective=objectiveML, cls, ...) ## S3 method for class 'semmodList' sem(model, S, N, data, raw=FALSE, fixed.x=NULL, robust=!missing(data), formula, group="Group", debug=FALSE, ...) ## S3 method for class 'msemmod' sem(model, S, N, start.fn=startvalues, group="Group", groups=names(model), raw=FALSE, fixed.x, param.names, var.names, debug=FALSE, analytic.gradient=TRUE, warn=FALSE, maxiter=5000, par.size = c("ones", "startvalues"), start.tol = 1e-06, start=c("initial.fit", "startvalues"), initial.maxiter=1000, optimizer = optimizerMsem, objective = msemObjectiveML, ...) startvalues(S, ram, debug=FALSE, tol=1E-6) startvalues2(S, ram, debug=FALSE, tol=1E-6) ## S3 method for class 'sem' coef(object, standardized=FALSE, ...) ## S3 method for class 'msem' coef(object, ...) ## S3 method for class 'sem' vcov(object, robust=FALSE, analytic=inherits(object, "objectiveML") && object$t <= 500, ...) ## S3 method for class 'msem' vcov(object, robust=FALSE, analytic=inherits(object, "msemObjectiveML") && object$t <= 500, ...) ## S3 method for class 'sem' df.residual(object, ...) ## S3 method for class 'msem' df.residual(object, ...)
model |
RAM specification, which is a simple encoding of the path
diagram for the model. The model may be given either in symbolic
form (as a |
S |
covariance matrix among observed variables; may be input as a symmetric matrix,
or as a lower- or upper-triangular matrix. |
N |
number of observations on which the covariance matrix is based; for a multigroup model, a vector
of group |
data |
As a generally preferable alternative to specifying |
start.fn |
a function to compute startvalues for the free parameters of the model;
two functions are supplied, |
na.action |
a function to process missing data, if raw data are supplied in the |
raw |
|
pattern.number , valid.data.patterns
|
these arguments pass information about valid (i.e., non-missing) data patterns and normally would not be specified directly by the user. |
use.means |
When raw data are supplied and intercepts are included in the model, use the
observed-variable means as start values for the intercepts; the default is |
obs.variables |
names of observed variables, by default taken from the row names of
the covariance or moment matrix |
fixed.x |
names (if the |
formula |
a one-sided formula, to be applied to |
robust |
In |
semmod |
a |
debug |
if |
... |
arguments to be passed down, including from |
param.names |
names of the |
var.names |
names of the |
analytic.gradient |
if |
warn |
if |
maxiter |
the maximum number of iterations for the optimization of the objective function, to be passed to the optimizer. |
par.size |
the anticipated size of the free parameters; if |
start.tol , tol
|
if the magnitude of an automatic start value is less than |
optimizer |
a function to be used to minimize the objective function; the default for single-group models is
|
objective |
An objective function to be minimized, sometimes called a “fit” function
in the SEM literature. The default for single-group models is |
cls |
primary class to be assigned to the result; normally this is not specified directly, but raither is inferred from the objective function. |
ram |
numeric RAM matrix. |
object |
an object of class |
standardized |
if |
analytic |
return an analytic (as opposed to numeric) estimate of the coefficient covariance matrix;
at present only available for the |
group |
for a multigroup model, the quoted name of the group variable; if the |
groups |
a character vector giving the names of the groups; will be ignored if |
start |
if |
initial.maxiter |
if |
The model is set up using either RAM (“reticular action model” – don't ask!)
notation – a simple format
for specifying general structural equation models by coding the
“arrows” in the path diagram for the model (see, e.g., McArdle and McDonald, 1984) –
typically using the specifyModel
function; in equation format using the
specifyEquations
function; or, for a simple confirmatory factor analysis model,
via the cfa
function. In any case, the model is represented internally in RAM format.
The variables in the vector in the model (typically, the observed and
unobserved variables, but not error variables) are numbered from 1 to
.
the RAM matrix contains one row for each (free or constrained) parameter of the model, and
may be specified either in symbolic format or in numeric format.
A symbolic ram
matrix consists of three columns, as follows:
This is a simple formula, of the form
"A -> B"
or, equivalently, "B <- A"
for a regression
coefficient (i.e., a single-headed or directional arrow);
"A <-> A"
for a variance or "A <-> B"
for a covariance
(i.e., a double-headed or bidirectional arrow). Here, A
and
B
are variable names in the model. If a name does not correspond
to an observed variable, then it is assumed to be a latent variable.
Spaces can appear freely in an arrow specification, and
there can be any number of hyphens in the arrows, including zero: Thus,
e.g., "A->B"
, "A --> B"
, and "A>B"
are all legitimate
and equivalent.
The name of the regression coefficient, variance,
or covariance specified by the arrow. Assigning the same name to two or
more arrows results in an equality constraint. Specifying the parameter name
as NA
produces a fixed parameter.
start value for a free parameter or value of a fixed parameter.
If given as NA
, sem
will compute the start value.
It is simplest to construct the RAM matrix with the specifyModel
, specifyEquations
,
or cfa
function,
all of which return an object of class semmod
, and also incorporate some model-specification
convenience shortcuts. This process is illustrated in the examples below.
A numeric ram
matrix consists of five columns, as follows:
1 (directed arrow) or 2 (covariance).
index of the variable at the head of
a directional arrow, or at one end of a bidirectional arrow.
Observed variables should be assigned the numbers 1 to , where
is the number of rows/columns in the covariance matrix
S
,
with the indices corresponding to the variables' positions in S
.
Variable indices above represent latent variables.
the index of the variable at the tail of a directional arrow, or at the other end of a bidirectional arrow.
free parameters are numbered from 1 to ,
but do not necessarily appear in consecutive order. Fixed parameters are given
the number 0. Equality contraints are specified by assigning two or more
parameters the same number.
start value for a free parameter, or value of a fixed parameter. If given
as NA
, the program will compute a start value, by a slight modification of the
method described by McDonald and Hartmann (1992). Note: In some circumstances,
some start values are selected randomly; this might produce small differences in
the parameter estimates when the program is rerun.
The numeric ram
matrix is normally generated automatically, not specified directly by the user.
For specifyEquations
, each input line is either a regression equation or the specification
of a variance or covariance. Regression equations are of the form
y = par1*x1 + par2*x2 + ... + park*xk
where y
and the x
s are variables in the model (either observed or latent),
and the par
s are parameters. If a parameter is given as a numeric value (e.g.,
1
) then it is treated as fixed. Note that no “error” variable is included in
the equation; “error variances” are specified via either the covs
argument,
via V(y) = par
(see immediately below), or are added automatically to the model
when, as by default, endog.variances=TRUE
.
Variances are specified in the form V(var) = par
and covariances in the form
C(var1, var2) = par
, where the var
s are variables (observed or unobserved) in
the model. The symbols V
and C
may be in either lower- or upper-case. If par
is a numeric value (e.g., 1
) then it is treated as fixed. In conformity with the RAM model,
a variance or covariance for an endogenous variable in the model is an “error” variance or
covariance.
To set a start value for a free parameter, enclose the numeric start value in parentheses after the
parameter name, as parameter(value)
.
sem
fits the model by calling the optimizer specified in the optimizer
argument
to minimize the objective function specified in the objective
argument.
If the optimization fails to converge, a warning message is printed.
The RAM formulation of the general structural equation model is given by the basic equation
where and
are vectors of random variables (observed or unobserved), and
the parameter matrix
contains regression coefficients, symbolized by single-headed arrows
in a path diagram. Another parameter matrix,
contains covariances among the elements of (assuming that the elements of
have zero
means). Usually
contains endogenous and exogenous observed and unobserved variables, but not
error variables (see the examples below).
The startvalues
function may be called directly, but is usually called by sem.default
; startvalues2
is an older version of this function that may be used alternatively; see the startvalues
argument to sem
.
sem
returns an object of class c(
objective, "sem")
, where objective
is the name of the objective function that was optimized (e.g., "objectiveML"
), with the following elements:
var.names |
vector of variable names. |
ram |
RAM matrix, including any rows generated for covariances among fixed exogenous variables; column 5 includes computed start values. |
S |
observed covariance matrix. |
J |
RAM selection matrix, |
n.fix |
number of fixed exogenous variables. |
n |
number of observed variables. |
N |
number of observations. |
m |
number of variables (observed plus unobserved). |
t |
number of free parameters. |
raw |
|
data |
the observed-variable data matrix, or |
semmod |
the |
optimizer |
the optimizer function. |
objective |
the objective function. |
coeff |
estimates of free parameters. |
vcov |
estimated asymptotic covariance matrix of parameter estimates, based on a numeric Hessian,
if supplied by the optimizer; otherwise |
par.posn |
indices of free parameters. |
convergence |
|
iterations |
number of iterations performed. |
criterion |
value of the objective function at the minimum. |
C |
model-reproduced covariance matrix. |
A |
RAM |
P |
RAM |
adj.obj |
robust adjusted value of the objective function; |
robust.vcov |
robust estimated coefficient covariance matrix; |
For multigroup models, sem
returns an object of class c("msemObjectiveML", "msem")
.
A common error is to fail to specify variance or covariance terms in the model, which are denoted
by double-headed arrows, <->
.
In general, every observed or latent variable in the model should be associated with a variance or error variance. This may be a free parameter to estimate or a fixed constant (as in the case of a latent exogenous variable for which you wish to fix the variance, e.g., to 1). Again in general, there will be an error variance associated with each endogenous variable in the model (i.e., each variable to which at least one single-headed arrow points — including observed indicators of latent variables), and a variance associated with each exogenous variable (i.e., each variable that appears only at the tail of single-headed arrows, never at the head).
To my knowledge, the only apparent exception to this rule is for observed variables that are declared to be fixed exogenous variables. In this case, the program generates the necessary (fixed-constant) variances and covariances automatically.
If there are missing variances, a warning message will be printed, and estimation will almost surely
fail in some manner. Missing
variances might well indicate that there are missing covariances too, but it is not possible
to deduce this in a mechanical manner. The specifyModel
funciton will by default supply
error-variance parameters if these are missing.
John Fox [email protected], Zhenghua Nie, and Jarrett Byrnes
Fox, J. (2006) Structural equation modeling with the sem package in R. Structural Equation Modeling 13:465–486.
Bollen, K. A. (1989) Structural Equations With Latent Variables. Wiley.
Bollen, K. A. and Long, J. S. (eds.) Testing Structural Equation Models, Sage.
McArdle, J. J. and Epstein, D. (1987) Latent growth curves within developmental structural equation models. Child Development 58, 110–133.
McArdle, J. J. and McDonald, R. P. (1984) Some algebraic properties of the reticular action model. British Journal of Mathematical and Statistical Psychology 37, 234–251.
McDonald, R. P. and Hartmann, W. M. (1992) A procedure for obtaining initial values of parameters in the RAM model. Multivariate Behavioral Research 27, 57–76.
Raftery, A. E. (1993) Bayesian model selection in structural equation models. In Bollen, K. A. and Long, J. S. (eds.) Testing Structural Equation Models, Sage.
Raftery, A. E. (1995) Bayesian model selection in social research (with discussion). Sociological Methodology 25, 111–196.
Satorra, A. (2000) Scaled and adjusted restricted tests in multi-sample analysis of moment structures. pp. 233–247 in Heijmans, R.D.H., Pollock, D.S.G. & Satorra, A. (eds.) Innovations in Multivariate Statistical Analysis. A Festschrift for Heinz Neudecker , Kluwer.
rawMoments
, startvalues
,
objectiveML
, objectiveGLS
,
optimizerNlm
, optimizerOptim
, optimizerNlminb
,
nlm
, optim
, nlminb
,
specifyModel
, specifyEquations
, cfa
# The following example illustrates the use the text argument to # readMoments() and specifyEquations(): R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp", text=" RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp ") sem.dhp.1 <- sem(model.dhp.1, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # Note: The following set of examples can't be run via example() because the default file # argument of specifyeEquations, specifyModel(), and readMoments() requires that the model # specification and covariances, correlations, or raw moments be entered in an interactive # session at the command prompt. The examples can be copied and run in the R console, # however. See ?specifyModel and ?readMoments for further information. # These examples are repeated below using file input to specifyModel() and # readMoments(). The second version of the examples may be executed through example(). ## Not run: # ------------- Duncan, Haller and Portes peer-influences model ---------------------- # A nonrecursive SEM with unobserved endogenous variables and fixed exogenous variables R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 # Fit the model using a symbolic ram specification model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA # an equivalent specification, allowing specifyModel() to generate # variance parameters for endogenous variables (and suppressing the # unnecessary NAs): model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 RGenAsp <-> FGenAsp, ps12 # Another equivalent specification, telling specifyModel to add paths for # variances and covariance of RGenAsp and FGenAsp: model.dhp <- specifyModel(covs="RGenAsp, FGenAsp") RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 # Yet another equivalent specification using specifyEquations(): model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp") RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp sem.dhp.1 <- sem(model.dhp.1, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # Fit the model using a numerical ram specification (not recommended!) ram.dhp <- matrix(c( # heads to from param start 1, 1, 11, 0, 1, 1, 2, 11, 1, NA, # lam21 1, 3, 12, 0, 1, 1, 4, 12, 2, NA, # lam42 1, 11, 5, 3, NA, # gam11 1, 11, 6, 4, NA, # gam12 1, 11, 7, 5, NA, # gam13 1, 11, 8, 6, NA, # gam14 1, 12, 7, 7, NA, # gam23 1, 12, 8, 8, NA, # gam24 1, 12, 9, 9, NA, # gam25 1, 12, 10, 10, NA, # gam26 1, 11, 12, 11, NA, # beta12 1, 12, 11, 12, NA, # beta21 2, 1, 1, 13, NA, # theta1 2, 2, 2, 14, NA, # theta2 2, 3, 3, 15, NA, # theta3 2, 4, 4, 16, NA, # theta4 2, 11, 11, 17, NA, # psi11 2, 12, 12, 18, NA, # psi22 2, 11, 12, 19, NA # psi12 ), ncol=5, byrow=TRUE) params.dhp <- c('lam21', 'lam42', 'gam11', 'gam12', 'gam13', 'gam14', 'gam23', 'gam24', 'gam25', 'gam26', 'beta12', 'beta21', 'theta1', 'theta2', 'theta3', 'theta4', 'psi11', 'psi22', 'psi12') vars.dhp <- c('ROccAsp', 'REdAsp', 'FOccAsp', 'FEdAsp', 'RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp', 'RGenAsp', 'FGenAsp') sem.dhp.2 <- sem(ram.dhp, R.DHP, 329, param.names=params.dhp, var.names=vars.dhp, fixed.x=5:10) summary(sem.dhp.2) # -------------------- Wheaton et al. alienation data ---------------------- S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 # This is the model in the SAS manual for PROC CALIS: A Recursive SEM with # latent endogenous and exogenous variables. # Curiously, both factor loadings for two of the latent variables are fixed. model.wh.1 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.1 <- sem(model.wh.1, S.wh, 932) summary(sem.wh.1) # The same model in equation format: model.wh.1 <- specifyEquations() Anomia67 = 1*Alienation67 Powerless67 = 0.833*Alienation67 Anomia71 = 1*Alienation71 Powerless71 = 0.833*Alienation71 Education = 1*SES SEI = lamb*SES Alienation67 = gam1*SES Alienation71 = gam2*SES + beta*Alienation67 V(Anomia67) = the1 V(Anomia71) = the1 V(Powerless67) = the2 V(Powerless71) = the2 V(SES) = phi C(Anomia67, Anomia71) = the5 C(Powerless67, Powerless71) = the5 # The same model, but treating one loading for each latent variable as free # (and equal to each other). model.wh.2 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, lamby, NA Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, lamby, NA SES -> Education, NA, 1 SES -> SEI, lambx, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.2 <- sem(model.wh.2, S.wh, 932) summary(sem.wh.2) # And again, in equation format: model.wh <- specifyEquations() Anomia67 = 1*Alienation67 Powerless67 = lamby*Alienation67 Anomia71 = 1*Alienation71 Powerless71 = lamby*Alienation71 Education = 1*SES SEI = lambx*SES Alienation67 = gam1*SES Alienation71 = gam2*SES + beta*Alienation67 V(Anomia67) = the1 V(Anomia71) = the1 V(Powerless67) = the2 V(Powerless71) = the2 V(SES) = phi C(Anomia67, Anomia71) = the5 C(Powerless67, Powerless71) = the5 # Compare the two models by a likelihood-ratio test: anova(sem.wh.1, sem.wh.2) # ----------------------- Thurstone data --------------------------------------- # Second-order confirmatory factor analysis, from the SAS manual for PROC CALIS R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 model.thur <- specifyModel() F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam42 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F4 -> F1, gam1 F4 -> F2, gam2 F4 -> F3, gam3 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 F4 <-> F4, NA, 1 sem.thur <- sem(model.thur, R.thur, 213) summary(sem.thur) # The model in equation format: model.thur <- specifyEquations() Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 F1 = gam1*F4 F2 = gam2*F4 F3 = gam3*F4 V(F1) = 1 V(F2) = 1 V(F3) = 1 V(F4) = 1 #------------------------- Kerchoff/Kenney path analysis --------------------- # An observed-variable recursive SEM from the LISREL manual R.kerch <- readMoments(diag=FALSE, names=c('Intelligence','Siblings', 'FatherEd','FatherOcc','Grades','EducExp','OccupAsp')) -.100 .277 -.152 .250 -.108 .611 .572 -.105 .294 .248 .489 -.213 .446 .410 .597 .335 -.153 .303 .331 .478 .651 model.kerch <- specifyModel() Intelligence -> Grades, gam51 Siblings -> Grades, gam52 FatherEd -> Grades, gam53 FatherOcc -> Grades, gam54 Intelligence -> EducExp, gam61 Siblings -> EducExp, gam62 FatherEd -> EducExp, gam63 FatherOcc -> EducExp, gam64 Grades -> EducExp, beta65 Intelligence -> OccupAsp, gam71 Siblings -> OccupAsp, gam72 FatherEd -> OccupAsp, gam73 FatherOcc -> OccupAsp, gam74 Grades -> OccupAsp, beta75 EducExp -> OccupAsp, beta76 sem.kerch <- sem(model.kerch, R.kerch, 737, fixed.x=c('Intelligence', 'Siblings', 'FatherEd', 'FatherOcc')) summary(sem.kerch) # The model in equation format: model.kerch <- specifyEquations() Grades = gam51*Intelligence + gam52*Siblings + gam53*FatherEd + gam54*FatherOcc EducExp = gam61*Intelligence + gam62*Siblings + gam63*FatherEd + gam64*FatherOcc + beta65*Grades OccupAsp = gam71*Intelligence + gam72*Siblings + gam73*FatherEd + gam74*FatherOcc + beta75*Grades + beta76*EducExp #------------------- McArdle/Epstein latent-growth-curve model ----------------- # This model, from McArdle and Epstein (1987, p.118), illustrates the use of a # raw moment matrix to fit a model with an intercept. (The example was suggested # by Mike Stoolmiller.) M.McArdle <- readMoments( names=c('WISC1', 'WISC2', 'WISC3', 'WISC4', 'UNIT')) 365.661 503.175 719.905 675.656 958.479 1303.392 890.680 1265.846 1712.475 2278.257 18.034 25.819 35.255 46.593 1.000 mod.McArdle <- specifyModel() C -> WISC1, NA, 6.07 C -> WISC2, B2, NA C -> WISC3, B3, NA C -> WISC4, B4, NA UNIT -> C, Mc, NA C <-> C, Vc, NA, WISC1 <-> WISC1, Vd, NA WISC2 <-> WISC2, Vd, NA WISC3 <-> WISC3, Vd, NA WISC4 <-> WISC4, Vd, NA sem.McArdle <- sem(mod.McArdle, M.McArdle, 204, fixed.x="UNIT", raw=TRUE) summary(sem.McArdle) # The model in equation format: mod.McArdle <- specifyEquations() WISC1 = 6.07*C WISC2 = B2*C WISC3 = B3*C WISC4 = b4*C C = Mc*UNIT v(C) = Vc v(WISC1) = Vd v(WISC2) = Vd v(WISC3) = Vd v(WISC4) = Vd #------------ Bollen industrialization and democracy example ----------------- # This model, from Bollen (1989, Ch. 8), illustrates the use in sem() of a # case-by-variable data (see ?Bollen) set rather than a covariance or moment matrix model.bollen <- specifyModel() Demo60 -> y1, NA, 1 Demo60 -> y2, lam2, Demo60 -> y3, lam3, Demo60 -> y4, lam4, Demo65 -> y5, NA, 1 Demo65 -> y6, lam2, Demo65 -> y7, lam3, Demo65 -> y8, lam4, Indust -> x1, NA, 1 Indust -> x2, lam6, Indust -> x3, lam7, y1 <-> y5, theta15 y2 <-> y4, theta24 y2 <-> y6, theta26 y3 <-> y7, theta37 y4 <-> y8, theta48 y6 <-> y8, theta68 Indust -> Demo60, gamma11, Indust -> Demo65, gamma21, Demo60 -> Demo65, beta21, Indust <-> Indust, phi sem.bollen <- sem(model.bollen, data=Bollen) summary(sem.bollen) summary(sem.bollen, robust=TRUE) # robust SEs and tests summary(sem.bollen, analytic.se=FALSE) # uses numeric rather than analytic Hessian # GLS rather than ML estimator: sem.bollen.gls <- sem(model.bollen, data=Bollen, objective=objectiveGLS) summary(sem.bollen.gls) # The model in equation format: model.bollen <- specifyEquations() y1 = 1*Demo60 y2 = lam2*Demo60 y3 = lam3*Demo60 y4 = lam4*Demo60 y5 = 1*Demo65 y6 = lam2*Demo65 y7 = lam3*Demo65 y8 = lam4*Demo65 x1 = 1*Indust x2 = lam6*Indust x3 = lam7*Indust c(y1, y5) = theta15 c(y2, y4) = theta24 c(y2, y6) = theta26 c(y3, y7) = theta37 c(y4, y8) = theta48 c(y6, y8) = theta68 Demo60 = gamma11*Indust Demo65 = gamma21*Indust + beta21*Demo60 v(Indust) = phi # -------------- A simple CFA model for the Thurstone mental tests data -------------- R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 # (1) in CFA format: mod.cfa.thur.c <- cfa(reference.indicators=FALSE) FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.c <- sem(mod.cfa.thur.c, R.thur, 213) summary(cfa.thur.c) # (2) in equation format: mod.cfa.thur.e <- specifyEquations(covs="F1, F2, F3") Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 V(F1) = 1 V(F2) = 1 V(F3) = 1 cfa.thur.e <- sem(mod.cfa.thur.e, R.thur, 213) summary(cfa.thur.e) # (3) in path format: mod.cfa.thur.p <- specifyModel(covs="F1, F2, F3") F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam41 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 cfa.thur.p <- sem(mod.cfa.thur.p, R.thur, 213) summary(cfa.thur.p) # ----- a CFA model fit by FIML to the mental-tests dataset with missing data ----- mod.cfa.tests <- cfa(raw=TRUE) verbal: x1, x2, x3 math: y1, y2, y3 cfa.tests <- sem(mod.cfa.tests, data=Tests, na.action=na.pass, objective=objectiveFIML, fixed.x="Intercept") summary(cfa.tests) summary(cfa.tests, saturated=TRUE) # takes time to fit saturated model for comparison # --- a multigroup CFA model fit to the Holzinger-Swineford mental-tests data ----- mod.hs <- cfa() spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) anova(sem.mg, sem.mg.eq) # test equality constraints ## End(Not run) ## =============================================================================== # The following examples use file input and may be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files # to get all fit indices (not recommended, but for illustration): opt <- options(fit.indices = c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC", "CAIC")) # ------------- Duncan, Haller and Portes peer-influences model ---------------------- # A nonrecursive SEM with unobserved endogenous variables and fixed exogenous variables (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) sem.dhp.1 <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # -------------------- Wheaton et al. alienation data ---------------------- (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) # This is the model in the SAS manual for PROC CALIS: A Recursive SEM with # latent endogenous and exogenous variables. # Curiously, both factor loadings for two of the latent variables are fixed. (model.wh.1 <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) sem.wh.1 <- sem(model.wh.1, S.wh, 932) summary(sem.wh.1) # The same model, but treating one loading for each latent variable as free # (and equal to each other). (model.wh.2 <- specifyModel(file=file.path(etc, "model-Wheaton-2.txt"))) sem.wh.2 <- sem(model.wh.2, S.wh, 932) summary(sem.wh.2) # Compare the two models by a likelihood-ratio test: anova(sem.wh.1, sem.wh.2) # ----------------------- Thurstone data --------------------------------------- # Second-order confirmatory factor analysis, from the SAS manual for PROC CALIS (R.thur <- readMoments(file=file.path(etc, "R-Thurstone.txt"), diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group'))) (model.thur <- specifyModel(file=file.path(etc, "model-Thurstone.txt"))) sem.thur <- sem(model.thur, R.thur, 213) summary(sem.thur) #------------------------- Kerchoff/Kenney path analysis --------------------- # An observed-variable recursive SEM from the LISREL manual (R.kerch <- readMoments(file=file.path(etc, "R-Kerchoff.txt"), diag=FALSE, names=c('Intelligence','Siblings', 'FatherEd','FatherOcc','Grades','EducExp','OccupAsp'))) (model.kerch <- specifyModel(file=file.path(etc, "model-Kerchoff.txt"))) sem.kerch <- sem(model.kerch, R.kerch, 737, fixed.x=c('Intelligence', 'Siblings', 'FatherEd', 'FatherOcc')) summary(sem.kerch) #------------------- McArdle/Epstein latent-growth-curve model ----------------- # This model, from McArdle and Epstein (1987, p.118), illustrates the use of a # raw moment matrix to fit a model with an intercept. (The example was suggested # by Mike Stoolmiller.) (M.McArdle <- readMoments(file=file.path(etc, "M-McArdle.txt"), names=c('WISC1', 'WISC2', 'WISC3', 'WISC4', 'UNIT'))) (mod.McArdle <- specifyModel(file=file.path(etc, "model-McArdle.txt"))) sem.McArdle <- sem(mod.McArdle, M.McArdle, 204, fixed.x="UNIT", raw=TRUE) summary(sem.McArdle) #------------ Bollen industrialization and democracy example ----------------- # This model, from Bollen (1989, Ch. 8), illustrates the use in sem() of a # case-by-variable data set (see ?Bollen) rather than a covariance or moment matrix (model.bollen <- specifyModel(file=file.path(etc, "model-Bollen.txt"))) sem.bollen <- sem(model.bollen, data=Bollen) summary(sem.bollen) summary(sem.bollen, robust=TRUE) # robust SEs and tests summary(sem.bollen, analytic.se=FALSE) # uses numeric rather than analytic Hessian # GLS rather than ML estimator: sem.bollen.gls <- sem(model.bollen, data=Bollen, objective=objectiveGLS) summary(sem.bollen.gls) # ----- a CFA model fit by FIML to the mental-tests dataset with missing data ----- (mod.cfa.tests <- cfa(file=file.path(etc, "model-Tests.txt"), raw=TRUE)) cfa.tests <- sem(mod.cfa.tests, data=Tests, na.action=na.pass, optimizer=optimizerNlm, objective=objectiveFIML, fixed.x="Intercept") summary(cfa.tests) #------------ Holzinger and Swineford muiltigroup CFA example ---------------- mod.hs <- cfa(file=file.path(etc, "model-HS.txt")) mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) anova(sem.mg, sem.mg.eq) # test equality constraints options(opt) # restore fit.indices option
# The following example illustrates the use the text argument to # readMoments() and specifyEquations(): R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"), text=" .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 ") model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp", text=" RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp ") sem.dhp.1 <- sem(model.dhp.1, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # Note: The following set of examples can't be run via example() because the default file # argument of specifyeEquations, specifyModel(), and readMoments() requires that the model # specification and covariances, correlations, or raw moments be entered in an interactive # session at the command prompt. The examples can be copied and run in the R console, # however. See ?specifyModel and ?readMoments for further information. # These examples are repeated below using file input to specifyModel() and # readMoments(). The second version of the examples may be executed through example(). ## Not run: # ------------- Duncan, Haller and Portes peer-influences model ---------------------- # A nonrecursive SEM with unobserved endogenous variables and fixed exogenous variables R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 # Fit the model using a symbolic ram specification model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA # an equivalent specification, allowing specifyModel() to generate # variance parameters for endogenous variables (and suppressing the # unnecessary NAs): model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 RGenAsp <-> FGenAsp, ps12 # Another equivalent specification, telling specifyModel to add paths for # variances and covariance of RGenAsp and FGenAsp: model.dhp <- specifyModel(covs="RGenAsp, FGenAsp") RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 # Yet another equivalent specification using specifyEquations(): model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp") RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp sem.dhp.1 <- sem(model.dhp.1, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # Fit the model using a numerical ram specification (not recommended!) ram.dhp <- matrix(c( # heads to from param start 1, 1, 11, 0, 1, 1, 2, 11, 1, NA, # lam21 1, 3, 12, 0, 1, 1, 4, 12, 2, NA, # lam42 1, 11, 5, 3, NA, # gam11 1, 11, 6, 4, NA, # gam12 1, 11, 7, 5, NA, # gam13 1, 11, 8, 6, NA, # gam14 1, 12, 7, 7, NA, # gam23 1, 12, 8, 8, NA, # gam24 1, 12, 9, 9, NA, # gam25 1, 12, 10, 10, NA, # gam26 1, 11, 12, 11, NA, # beta12 1, 12, 11, 12, NA, # beta21 2, 1, 1, 13, NA, # theta1 2, 2, 2, 14, NA, # theta2 2, 3, 3, 15, NA, # theta3 2, 4, 4, 16, NA, # theta4 2, 11, 11, 17, NA, # psi11 2, 12, 12, 18, NA, # psi22 2, 11, 12, 19, NA # psi12 ), ncol=5, byrow=TRUE) params.dhp <- c('lam21', 'lam42', 'gam11', 'gam12', 'gam13', 'gam14', 'gam23', 'gam24', 'gam25', 'gam26', 'beta12', 'beta21', 'theta1', 'theta2', 'theta3', 'theta4', 'psi11', 'psi22', 'psi12') vars.dhp <- c('ROccAsp', 'REdAsp', 'FOccAsp', 'FEdAsp', 'RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp', 'RGenAsp', 'FGenAsp') sem.dhp.2 <- sem(ram.dhp, R.DHP, 329, param.names=params.dhp, var.names=vars.dhp, fixed.x=5:10) summary(sem.dhp.2) # -------------------- Wheaton et al. alienation data ---------------------- S.wh <- readMoments(names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI')) 11.834 6.947 9.364 6.819 5.091 12.532 4.783 5.028 7.495 9.986 -3.839 -3.889 -3.841 -3.625 9.610 -21.899 -18.831 -21.748 -18.775 35.522 450.288 # This is the model in the SAS manual for PROC CALIS: A Recursive SEM with # latent endogenous and exogenous variables. # Curiously, both factor loadings for two of the latent variables are fixed. model.wh.1 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, NA, 0.833 Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, NA, 0.833 SES -> Education, NA, 1 SES -> SEI, lamb, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.1 <- sem(model.wh.1, S.wh, 932) summary(sem.wh.1) # The same model in equation format: model.wh.1 <- specifyEquations() Anomia67 = 1*Alienation67 Powerless67 = 0.833*Alienation67 Anomia71 = 1*Alienation71 Powerless71 = 0.833*Alienation71 Education = 1*SES SEI = lamb*SES Alienation67 = gam1*SES Alienation71 = gam2*SES + beta*Alienation67 V(Anomia67) = the1 V(Anomia71) = the1 V(Powerless67) = the2 V(Powerless71) = the2 V(SES) = phi C(Anomia67, Anomia71) = the5 C(Powerless67, Powerless71) = the5 # The same model, but treating one loading for each latent variable as free # (and equal to each other). model.wh.2 <- specifyModel() Alienation67 -> Anomia67, NA, 1 Alienation67 -> Powerless67, lamby, NA Alienation71 -> Anomia71, NA, 1 Alienation71 -> Powerless71, lamby, NA SES -> Education, NA, 1 SES -> SEI, lambx, NA SES -> Alienation67, gam1, NA Alienation67 -> Alienation71, beta, NA SES -> Alienation71, gam2, NA Anomia67 <-> Anomia67, the1, NA Anomia71 <-> Anomia71, the1, NA Powerless67 <-> Powerless67, the2, NA Powerless71 <-> Powerless71, the2, NA Education <-> Education, the3, NA SEI <-> SEI, the4, NA Anomia67 <-> Anomia71, the5, NA Powerless67 <-> Powerless71, the5, NA Alienation67 <-> Alienation67, psi1, NA Alienation71 <-> Alienation71, psi2, NA SES <-> SES, phi, NA sem.wh.2 <- sem(model.wh.2, S.wh, 932) summary(sem.wh.2) # And again, in equation format: model.wh <- specifyEquations() Anomia67 = 1*Alienation67 Powerless67 = lamby*Alienation67 Anomia71 = 1*Alienation71 Powerless71 = lamby*Alienation71 Education = 1*SES SEI = lambx*SES Alienation67 = gam1*SES Alienation71 = gam2*SES + beta*Alienation67 V(Anomia67) = the1 V(Anomia71) = the1 V(Powerless67) = the2 V(Powerless71) = the2 V(SES) = phi C(Anomia67, Anomia71) = the5 C(Powerless67, Powerless71) = the5 # Compare the two models by a likelihood-ratio test: anova(sem.wh.1, sem.wh.2) # ----------------------- Thurstone data --------------------------------------- # Second-order confirmatory factor analysis, from the SAS manual for PROC CALIS R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 model.thur <- specifyModel() F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam42 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F4 -> F1, gam1 F4 -> F2, gam2 F4 -> F3, gam3 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 F4 <-> F4, NA, 1 sem.thur <- sem(model.thur, R.thur, 213) summary(sem.thur) # The model in equation format: model.thur <- specifyEquations() Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 F1 = gam1*F4 F2 = gam2*F4 F3 = gam3*F4 V(F1) = 1 V(F2) = 1 V(F3) = 1 V(F4) = 1 #------------------------- Kerchoff/Kenney path analysis --------------------- # An observed-variable recursive SEM from the LISREL manual R.kerch <- readMoments(diag=FALSE, names=c('Intelligence','Siblings', 'FatherEd','FatherOcc','Grades','EducExp','OccupAsp')) -.100 .277 -.152 .250 -.108 .611 .572 -.105 .294 .248 .489 -.213 .446 .410 .597 .335 -.153 .303 .331 .478 .651 model.kerch <- specifyModel() Intelligence -> Grades, gam51 Siblings -> Grades, gam52 FatherEd -> Grades, gam53 FatherOcc -> Grades, gam54 Intelligence -> EducExp, gam61 Siblings -> EducExp, gam62 FatherEd -> EducExp, gam63 FatherOcc -> EducExp, gam64 Grades -> EducExp, beta65 Intelligence -> OccupAsp, gam71 Siblings -> OccupAsp, gam72 FatherEd -> OccupAsp, gam73 FatherOcc -> OccupAsp, gam74 Grades -> OccupAsp, beta75 EducExp -> OccupAsp, beta76 sem.kerch <- sem(model.kerch, R.kerch, 737, fixed.x=c('Intelligence', 'Siblings', 'FatherEd', 'FatherOcc')) summary(sem.kerch) # The model in equation format: model.kerch <- specifyEquations() Grades = gam51*Intelligence + gam52*Siblings + gam53*FatherEd + gam54*FatherOcc EducExp = gam61*Intelligence + gam62*Siblings + gam63*FatherEd + gam64*FatherOcc + beta65*Grades OccupAsp = gam71*Intelligence + gam72*Siblings + gam73*FatherEd + gam74*FatherOcc + beta75*Grades + beta76*EducExp #------------------- McArdle/Epstein latent-growth-curve model ----------------- # This model, from McArdle and Epstein (1987, p.118), illustrates the use of a # raw moment matrix to fit a model with an intercept. (The example was suggested # by Mike Stoolmiller.) M.McArdle <- readMoments( names=c('WISC1', 'WISC2', 'WISC3', 'WISC4', 'UNIT')) 365.661 503.175 719.905 675.656 958.479 1303.392 890.680 1265.846 1712.475 2278.257 18.034 25.819 35.255 46.593 1.000 mod.McArdle <- specifyModel() C -> WISC1, NA, 6.07 C -> WISC2, B2, NA C -> WISC3, B3, NA C -> WISC4, B4, NA UNIT -> C, Mc, NA C <-> C, Vc, NA, WISC1 <-> WISC1, Vd, NA WISC2 <-> WISC2, Vd, NA WISC3 <-> WISC3, Vd, NA WISC4 <-> WISC4, Vd, NA sem.McArdle <- sem(mod.McArdle, M.McArdle, 204, fixed.x="UNIT", raw=TRUE) summary(sem.McArdle) # The model in equation format: mod.McArdle <- specifyEquations() WISC1 = 6.07*C WISC2 = B2*C WISC3 = B3*C WISC4 = b4*C C = Mc*UNIT v(C) = Vc v(WISC1) = Vd v(WISC2) = Vd v(WISC3) = Vd v(WISC4) = Vd #------------ Bollen industrialization and democracy example ----------------- # This model, from Bollen (1989, Ch. 8), illustrates the use in sem() of a # case-by-variable data (see ?Bollen) set rather than a covariance or moment matrix model.bollen <- specifyModel() Demo60 -> y1, NA, 1 Demo60 -> y2, lam2, Demo60 -> y3, lam3, Demo60 -> y4, lam4, Demo65 -> y5, NA, 1 Demo65 -> y6, lam2, Demo65 -> y7, lam3, Demo65 -> y8, lam4, Indust -> x1, NA, 1 Indust -> x2, lam6, Indust -> x3, lam7, y1 <-> y5, theta15 y2 <-> y4, theta24 y2 <-> y6, theta26 y3 <-> y7, theta37 y4 <-> y8, theta48 y6 <-> y8, theta68 Indust -> Demo60, gamma11, Indust -> Demo65, gamma21, Demo60 -> Demo65, beta21, Indust <-> Indust, phi sem.bollen <- sem(model.bollen, data=Bollen) summary(sem.bollen) summary(sem.bollen, robust=TRUE) # robust SEs and tests summary(sem.bollen, analytic.se=FALSE) # uses numeric rather than analytic Hessian # GLS rather than ML estimator: sem.bollen.gls <- sem(model.bollen, data=Bollen, objective=objectiveGLS) summary(sem.bollen.gls) # The model in equation format: model.bollen <- specifyEquations() y1 = 1*Demo60 y2 = lam2*Demo60 y3 = lam3*Demo60 y4 = lam4*Demo60 y5 = 1*Demo65 y6 = lam2*Demo65 y7 = lam3*Demo65 y8 = lam4*Demo65 x1 = 1*Indust x2 = lam6*Indust x3 = lam7*Indust c(y1, y5) = theta15 c(y2, y4) = theta24 c(y2, y6) = theta26 c(y3, y7) = theta37 c(y4, y8) = theta48 c(y6, y8) = theta68 Demo60 = gamma11*Indust Demo65 = gamma21*Indust + beta21*Demo60 v(Indust) = phi # -------------- A simple CFA model for the Thurstone mental tests data -------------- R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 # (1) in CFA format: mod.cfa.thur.c <- cfa(reference.indicators=FALSE) FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.c <- sem(mod.cfa.thur.c, R.thur, 213) summary(cfa.thur.c) # (2) in equation format: mod.cfa.thur.e <- specifyEquations(covs="F1, F2, F3") Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 V(F1) = 1 V(F2) = 1 V(F3) = 1 cfa.thur.e <- sem(mod.cfa.thur.e, R.thur, 213) summary(cfa.thur.e) # (3) in path format: mod.cfa.thur.p <- specifyModel(covs="F1, F2, F3") F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam41 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 cfa.thur.p <- sem(mod.cfa.thur.p, R.thur, 213) summary(cfa.thur.p) # ----- a CFA model fit by FIML to the mental-tests dataset with missing data ----- mod.cfa.tests <- cfa(raw=TRUE) verbal: x1, x2, x3 math: y1, y2, y3 cfa.tests <- sem(mod.cfa.tests, data=Tests, na.action=na.pass, objective=objectiveFIML, fixed.x="Intercept") summary(cfa.tests) summary(cfa.tests, saturated=TRUE) # takes time to fit saturated model for comparison # --- a multigroup CFA model fit to the Holzinger-Swineford mental-tests data ----- mod.hs <- cfa() spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) anova(sem.mg, sem.mg.eq) # test equality constraints ## End(Not run) ## =============================================================================== # The following examples use file input and may be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files # to get all fit indices (not recommended, but for illustration): opt <- options(fit.indices = c("GFI", "AGFI", "RMSEA", "NFI", "NNFI", "CFI", "RNI", "IFI", "SRMR", "AIC", "AICc", "BIC", "CAIC")) # ------------- Duncan, Haller and Portes peer-influences model ---------------------- # A nonrecursive SEM with unobserved endogenous variables and fixed exogenous variables (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) sem.dhp.1 <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) summary(sem.dhp.1) # -------------------- Wheaton et al. alienation data ---------------------- (S.wh <- readMoments(file=file.path(etc, "S-Wheaton.txt"), names=c('Anomia67','Powerless67','Anomia71', 'Powerless71','Education','SEI'))) # This is the model in the SAS manual for PROC CALIS: A Recursive SEM with # latent endogenous and exogenous variables. # Curiously, both factor loadings for two of the latent variables are fixed. (model.wh.1 <- specifyModel(file=file.path(etc, "model-Wheaton-1.txt"))) sem.wh.1 <- sem(model.wh.1, S.wh, 932) summary(sem.wh.1) # The same model, but treating one loading for each latent variable as free # (and equal to each other). (model.wh.2 <- specifyModel(file=file.path(etc, "model-Wheaton-2.txt"))) sem.wh.2 <- sem(model.wh.2, S.wh, 932) summary(sem.wh.2) # Compare the two models by a likelihood-ratio test: anova(sem.wh.1, sem.wh.2) # ----------------------- Thurstone data --------------------------------------- # Second-order confirmatory factor analysis, from the SAS manual for PROC CALIS (R.thur <- readMoments(file=file.path(etc, "R-Thurstone.txt"), diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group'))) (model.thur <- specifyModel(file=file.path(etc, "model-Thurstone.txt"))) sem.thur <- sem(model.thur, R.thur, 213) summary(sem.thur) #------------------------- Kerchoff/Kenney path analysis --------------------- # An observed-variable recursive SEM from the LISREL manual (R.kerch <- readMoments(file=file.path(etc, "R-Kerchoff.txt"), diag=FALSE, names=c('Intelligence','Siblings', 'FatherEd','FatherOcc','Grades','EducExp','OccupAsp'))) (model.kerch <- specifyModel(file=file.path(etc, "model-Kerchoff.txt"))) sem.kerch <- sem(model.kerch, R.kerch, 737, fixed.x=c('Intelligence', 'Siblings', 'FatherEd', 'FatherOcc')) summary(sem.kerch) #------------------- McArdle/Epstein latent-growth-curve model ----------------- # This model, from McArdle and Epstein (1987, p.118), illustrates the use of a # raw moment matrix to fit a model with an intercept. (The example was suggested # by Mike Stoolmiller.) (M.McArdle <- readMoments(file=file.path(etc, "M-McArdle.txt"), names=c('WISC1', 'WISC2', 'WISC3', 'WISC4', 'UNIT'))) (mod.McArdle <- specifyModel(file=file.path(etc, "model-McArdle.txt"))) sem.McArdle <- sem(mod.McArdle, M.McArdle, 204, fixed.x="UNIT", raw=TRUE) summary(sem.McArdle) #------------ Bollen industrialization and democracy example ----------------- # This model, from Bollen (1989, Ch. 8), illustrates the use in sem() of a # case-by-variable data set (see ?Bollen) rather than a covariance or moment matrix (model.bollen <- specifyModel(file=file.path(etc, "model-Bollen.txt"))) sem.bollen <- sem(model.bollen, data=Bollen) summary(sem.bollen) summary(sem.bollen, robust=TRUE) # robust SEs and tests summary(sem.bollen, analytic.se=FALSE) # uses numeric rather than analytic Hessian # GLS rather than ML estimator: sem.bollen.gls <- sem(model.bollen, data=Bollen, objective=objectiveGLS) summary(sem.bollen.gls) # ----- a CFA model fit by FIML to the mental-tests dataset with missing data ----- (mod.cfa.tests <- cfa(file=file.path(etc, "model-Tests.txt"), raw=TRUE)) cfa.tests <- sem(mod.cfa.tests, data=Tests, na.action=na.pass, optimizer=optimizerNlm, objective=objectiveFIML, fixed.x="Intercept") summary(cfa.tests) #------------ Holzinger and Swineford muiltigroup CFA example ---------------- mod.hs <- cfa(file=file.path(etc, "model-HS.txt")) mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) anova(sem.mg, sem.mg.eq) # test equality constraints options(opt) # restore fit.indices option
These functions are provided for compatibility with older versions of the sem package only, and may be removed eventually. Although an effort has been made to insure backwards-compatibility, commands that worked in versions of the sem package prior to version 2.0-0 will not necessarily work in version 2.0-0 and beyond, or may not work in the same manner.
boot.sem(...) mod.indices(...) normalized.residuals(...) path.diagram(...) raw.moments(...) read.moments(...) specify.model(...) standardized.coefficients(...) standardized.residuals(...) std.coef(...)
boot.sem(...) mod.indices(...) normalized.residuals(...) path.diagram(...) raw.moments(...) read.moments(...) specify.model(...) standardized.coefficients(...) standardized.residuals(...) std.coef(...)
... |
pass arguments down to replacements for deprecated functions. |
boot.sem
is now a synonym for the bootSem
function.
mod.indices
is now a synonym for modIndices
.
normalized.residuals
is now a synonym for normalizedResiduals
.
path.diagram
is now a synonym for pathDiagram
.
raw.moments
is now a synonym for rawMoments
.
read.moments
is now a synonym for readMoments
.
specify.model
is now a synonym for specifyModel
.
standardized.coefficients
and std.coef
are now synonyms for the standardizedCoefficients
and stdCoef
functions.
standardized.residuals
is now a synonym for standardizedResiduals
.
Create the RAM specification of a structural equation model.
specifyModel(file="", text, exog.variances=FALSE, endog.variances=TRUE, covs, suffix="", quiet=FALSE) specifyEquations(file="", text, ...) cfa(file="", text, covs=paste(factors, collapse=","), reference.indicators=TRUE, raw=FALSE, subscript=c("name", "number"), ...) multigroupModel(..., groups=names(models), allEqual=FALSE) classifyVariables(model) removeRedundantPaths(model, warn=TRUE) ## S3 method for class 'semmod' combineModels(..., warn=TRUE) ## S3 method for class 'semmod' update(object, file = "", text, ...) ## S3 method for class 'semmod' edit(name, ...) ## S3 method for class 'semmod' print(x, ...) ## S3 method for class 'semmodList' print(x, ...)
specifyModel(file="", text, exog.variances=FALSE, endog.variances=TRUE, covs, suffix="", quiet=FALSE) specifyEquations(file="", text, ...) cfa(file="", text, covs=paste(factors, collapse=","), reference.indicators=TRUE, raw=FALSE, subscript=c("name", "number"), ...) multigroupModel(..., groups=names(models), allEqual=FALSE) classifyVariables(model) removeRedundantPaths(model, warn=TRUE) ## S3 method for class 'semmod' combineModels(..., warn=TRUE) ## S3 method for class 'semmod' update(object, file = "", text, ...) ## S3 method for class 'semmod' edit(name, ...) ## S3 method for class 'semmod' print(x, ...) ## S3 method for class 'semmodList' print(x, ...)
file |
The (quoted) file from which to read the model specification,
including the path to the file if it is not in the current directory. If
|
text |
The model specification given as a character string, as an alternative
to specifying the ] |
exog.variances |
If |
endog.variances |
If |
covs |
optional: a character vector of one or more elements, with each element
giving a string of variable names, separated by commas. Variances and covariances
among all variables in each such string are added to the model. For confirmatory
factor analysis models specified via |
suffix |
a character string (defaulting to an empty string) to be appended to each parameter name; this can be convenient for specifying multiple-group models. |
reference.indicators |
if |
raw |
if |
subscript |
The “subscripts” to be appended to |
quiet |
if |
x , model , object , name
|
An object of class |
warn |
print a warning if redundant paths are detected. |
... |
For |
groups |
a character vector of names for the groups in a multigroup model; taken by default from
the names of the |
allEqual |
if |
The principal functions for model specification are specifyModel
,
to specify a model in RAM (path) format via single- and double-headed arrows;
specifyEquations
, to specify a model in equation format, which is then
translated by the function into RAM format; and cfa
, for compact
specification of simple confirmatory factor analysis models.
specifyModel
:
Each line of the RAM specification for specifyModel
consists of three (unquoted) entries,
separated by commas:
This is a simple formula, of the form
A -> B
or, equivalently, B <- A
for a regression
coefficient (i.e., a single-headed or directional arrow);
A <-> A
for a variance or A <-> B
for a covariance
(i.e., a double-headed or bidirectional arrow). Here, A
and
B
are variable names in the model. If a name does not correspond
to an observed variable, then it is assumed to be a latent variable.
Spaces can appear freely in an arrow specification, and
there can be any number of hyphens in the arrows, including zero: Thus,
e.g., A->B
, A --> B
, and A>B
are all legitimate
and equivalent.
The name of the regression coefficient, variance,
or covariance specified by the arrow. Assigning the same name to two or
more arrows results in an equality constraint. Specifying the parameter name
as NA
produces a fixed parameter.
start value for a free parameter or value of a fixed parameter.
If given as NA
(or simply omitted), sem
will compute the start value.
Lines may end in a comment following #
.
specifyEquations
:
For specifyEquations
, each input line is either a regression equation or the specification
of a variance or covariance. Regression equations are of the form
y = par1*x1 + par2*x2 + ... + park*xk
where y
and the x
s are variables in the model (either observed or latent),
and the par
s are parameters. If a parameter is given as a numeric value (e.g.,
1
) then it is treated as fixed. Note that no “error” variable is included in
the equation; “error variances” are specified via either the covs
argument,
via V(y) = par
(see immediately below), or are added automatically to the model
when, as by default, endog.variances=TRUE
. A regression equation may be split over more
than one input by breaking at a +
, so that +
is either the last non-blank character
on a line or the first non-blank character on the subsequent line.
Variances are specified in the form V(var) = par
and covariances in the form
C(var1, var2) = par
, where the var
s are variables (observed or unobserved) in
the model. The symbols V
and C
may be in either lower- or upper-case. If par
is a numeric value (e.g., 1
) then it is treated as fixed. In conformity with the RAM model,
a variance or covariance for an endogenous variable in the model is an “error” variance or
covariance.
Warning: If the covs
argument to specifyEquations
is used to specify
variances and covariances, please be aware that
covs="x1, x2"
and covs=c("x1", "x2")
are not
equivalent: covs="x1, x2"
specifies the variance of x1
, the variance
of x2
, and their covariance, while covs=c("x1", "x2")
specifies
the variance of x1
and the variance of x2
but not their covariance.
To set a start value for a free parameter, enclose the numeric start value in parentheses after the
parameter name, as parameter(value)
.
cfa
:
For cfa
, each input line includes the names of the variables, separated by commas,
that load on the corresponding factor; the name of the factor is given optionally at the beginning
of the line, followed by a colon. If necessary, the variables that load on a factor may be continued
across two or more input lines; in this case, each such line but the last must end in a comma. A
variable may load on more than one factor (as long as the resulting model is identified, of course),
but each factor may appear in only one input line (or set of input lines, if the variable list
is continued onto the next line).
Equality constraints for factor loadings can be set by using equal-signs (=
) rather than commas
to separate observed variable names. For example, fac1: x1=x2=x3, x4=x5
sets the loadings
for x1
, x2
, and x3
equal to each other, and the loadings for x4
and x5
equal to each other.
Equality constraints among error variances can similarly be specified by using var:
or variance:
at the beginning of a line (actually, any character string beginning with var
will do, and thus
no factor name may begin with the characters var
). For example, var: x1=x2=x3, x4=x5
sets the
error variances for x1
, x2
, and x3
equal to each other, and the
error variances for x4
and x5
equal to each other. There may be several lines beginning with
var:
.
If the argument reference.indicators=FALSE
, the default,
cfa
will fix the variance of each factor to 1, and by
default include covariances (i.e., correlations) among all pairs of factors. Alternatively,
if reference.indicators=TRUE
, then the factor variances are free parameters to be estimated
from the data, and the first loading for each factor is set to 1 to identify the model. These two
approaches produce equivalent models, with the same fit to the data, but alternative parametrizations.
Specifying the argument covs=NULL
implicitly fixes the factor intercorrelations to 0.
See sem
and the examples for further details on model specification.
Other Functions:
classifyVariables
classifies the variables in a model as endogenous or exogenous.
combineModels
and removeRedundantPaths
take semmod
objects as arguments and do what their names imply.
The file
input argument to the update
method for semmod
objects, which by default comes from
standard input, is a set of update directives, one per line. There are five kinds of directives. In each case
the directive begins with the directive name, followed by one or more fields separated by commas.
Remove a path from the model. Example: delete, RSES -> FGenAsp
Add a path to the model. Example (the NA
for the start value is optional): add, RSES -> FGenAsp, gam14, NA
Replace every occurrence of the first string with the second in the variables and
parameters of the model. This directive may be used, for example, to change one variable to
another or to rename a parameter. Example: replace, gam, gamma
, substitutes the string "gamma"
for "gam"
wherever the latter appears, presumably in parameter names.
Fix a parameter that was formerly free. Example: fix, RGenAsp -> REdAsp, 1
Free a parameter that was formerly fixed. Example (the NA
for the start value is optional):
free, RGenAsp -> ROccAsp, lam11, NA
The edit
method for semmod
objects opens the model in the R editor.
specifyModel
, specifyEquations
, cfa
, removeRedundantPaths
, combineModels
,
update
, and edit
return an object of class semmod
, suitable as input for sem
.
multigroupModel
returns an object of class semmodList
, also suitable as input for sem
.
classifyVariables
returns a list with two character vectors: endogenous
, containing the names of endogenous
variables in the model; and exogenous
, containing the names of exogenous variables.
John Fox [email protected] and Jarrett Byrnes
# example using the text argument: model.dhp <- specifyModel(text=" RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA ") model.dhp # same model in equation form: model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp", text=" RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp ") model.dhp # Note: The following examples can't be run via example() because the # default file argument requires that the model specification be entered # at the command prompt. The examples can be copied and run in an interactive # session in the R console, however. ## Not run: model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA model.dhp # an equivalent specification, allowing specifyModel() to generate # variance parameters for endogenous variables (and suppressing # the unnecessary trailing NAs): model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 RGenAsp <-> FGenAsp, ps12 model.dhp # Another equivalent specification, telling specifyModel to add paths for # variances and covariance of RGenAsp and FGenAsp: model.dhp <- specifyModel(covs="RGenAsp, FGenAsp") RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 model.dhp # The same model in equation format: model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp") RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp model.dhp classifyVariables(model.dhp) # updating the model to impose equality constraints # and to rename the latent variables and gamma parameters model.dhp.eq <- update(model.dhp) delete, RSES -> FGenAsp delete, FSES -> FGenAsp delete, FIQ -> FGenAsp delete, FParAsp -> FGenAs delete, RGenAsp -> FGenAsp add, RSES -> FGenAsp, gam14, NA add, FSES -> FGenAsp, gam13, NA add, FIQ -> FGenAsp, gam12, NA add, FParAsp -> FGenAsp, gam26, NA add, RGenAsp -> FGenAsp, beta12, NA replace, gam, gamma replace, Gen, General model.dhp.eq # A three-factor CFA model for the Thurstone mental-tests data, # specified three equivalent ways: R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 # (1a) in CFA format: mod.cfa.thur.c <- cfa(reference.indicators=FALSE) FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.c <- sem(mod.cfa.thur.c, R.thur, 213) summary(cfa.thur.c) # (1b) in CFA format, using reference indicators: mod.cfa.thur.r <- cfa() FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.r <- sem(mod.cfa.thur.r, R.thur, 213) summary(cfa.thur.r) # (2) in equation format: mod.cfa.thur.e <- specifyEquations(covs="F1, F2, F3") Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 V(F1) = 1 V(F2) = 1 V(F3) = 1 cfa.thur.e <- sem(mod.cfa.thur.e, R.thur, 213) summary(cfa.thur.e) # (3) in path format: mod.cfa.thur.p <- specifyModel(covs="F1, F2, F3") F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam41 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 cfa.thur.p <- sem(mod.cfa.thur.p, R.thur, 213) summary(cfa.thur.p) # The Thursstone CFA model with equality constraints on the # factor loadings and error variances mod.cfa.thur.ceq <- cfa(reference.indicators=FALSE) FA: Sentences = Vocabulary = Sent.Completion FB: First.Letters = 4.Letter.Words = Suffixes FC: Letter.Series = Pedigrees = Letter.Group var: Sentences = Vocabulary = Sent.Completion var: First.Letters = 4.Letter.Words = Suffixes var: Letter.Series = Pedigrees = Letter.Group cfa.thur.ceq <- sem(mod.cfa.thur.ceq, R.thur, 213) summary(cfa.thur.ceq) anova(cfa.thur.c, cfa.thur.ceq) pathDiagram(cfa.thur.ceq, ignore.double=FALSE, ignore.self=TRUE, min.rank="FA, FB, FC", edge.labels="values") # a multigroup CFA model fit to the Holzinger-Swineford # mental-tests data mod.hs <- cfa() spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) ## End(Not run)
# example using the text argument: model.dhp <- specifyModel(text=" RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA ") model.dhp # same model in equation form: model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp", text=" RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp ") model.dhp # Note: The following examples can't be run via example() because the # default file argument requires that the model specification be entered # at the command prompt. The examples can be copied and run in an interactive # session in the R console, however. ## Not run: model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA model.dhp # an equivalent specification, allowing specifyModel() to generate # variance parameters for endogenous variables (and suppressing # the unnecessary trailing NAs): model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 RGenAsp <-> FGenAsp, ps12 model.dhp # Another equivalent specification, telling specifyModel to add paths for # variances and covariance of RGenAsp and FGenAsp: model.dhp <- specifyModel(covs="RGenAsp, FGenAsp") RParAsp -> RGenAsp, gam11 RIQ -> RGenAsp, gam12 RSES -> RGenAsp, gam13 FSES -> RGenAsp, gam14 RSES -> FGenAsp, gam23 FSES -> FGenAsp, gam24 FIQ -> FGenAsp, gam25 FParAsp -> FGenAsp, gam26 FGenAsp -> RGenAsp, beta12 RGenAsp -> FGenAsp, beta21 RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21 FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42 model.dhp # The same model in equation format: model.dhp.1 <- specifyEquations(covs="RGenAsp, FGenAsp") RGenAsp = gam11*RParAsp + gam12*RIQ + gam13*RSES + gam14*FSES + beta12*FGenAsp FGenAsp = gam23*RSES + gam24*FSES + gam25*FIQ + gam26*FParAsp + beta21*RGenAsp ROccAsp = 1*RGenAsp REdAsp = lam21(1)*RGenAsp # to illustrate setting start values FOccAsp = 1*FGenAsp FEdAsp = lam42(1)*FGenAsp model.dhp classifyVariables(model.dhp) # updating the model to impose equality constraints # and to rename the latent variables and gamma parameters model.dhp.eq <- update(model.dhp) delete, RSES -> FGenAsp delete, FSES -> FGenAsp delete, FIQ -> FGenAsp delete, FParAsp -> FGenAs delete, RGenAsp -> FGenAsp add, RSES -> FGenAsp, gam14, NA add, FSES -> FGenAsp, gam13, NA add, FIQ -> FGenAsp, gam12, NA add, FParAsp -> FGenAsp, gam26, NA add, RGenAsp -> FGenAsp, beta12, NA replace, gam, gamma replace, Gen, General model.dhp.eq # A three-factor CFA model for the Thurstone mental-tests data, # specified three equivalent ways: R.thur <- readMoments(diag=FALSE, names=c('Sentences','Vocabulary', 'Sent.Completion','First.Letters','4.Letter.Words','Suffixes', 'Letter.Series','Pedigrees', 'Letter.Group')) .828 .776 .779 .439 .493 .46 .432 .464 .425 .674 .447 .489 .443 .59 .541 .447 .432 .401 .381 .402 .288 .541 .537 .534 .35 .367 .32 .555 .38 .358 .359 .424 .446 .325 .598 .452 # (1a) in CFA format: mod.cfa.thur.c <- cfa(reference.indicators=FALSE) FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.c <- sem(mod.cfa.thur.c, R.thur, 213) summary(cfa.thur.c) # (1b) in CFA format, using reference indicators: mod.cfa.thur.r <- cfa() FA: Sentences, Vocabulary, Sent.Completion FB: First.Letters, 4.Letter.Words, Suffixes FC: Letter.Series, Pedigrees, Letter.Group cfa.thur.r <- sem(mod.cfa.thur.r, R.thur, 213) summary(cfa.thur.r) # (2) in equation format: mod.cfa.thur.e <- specifyEquations(covs="F1, F2, F3") Sentences = lam11*F1 Vocabulary = lam21*F1 Sent.Completion = lam31*F1 First.Letters = lam42*F2 4.Letter.Words = lam52*F2 Suffixes = lam62*F2 Letter.Series = lam73*F3 Pedigrees = lam83*F3 Letter.Group = lam93*F3 V(F1) = 1 V(F2) = 1 V(F3) = 1 cfa.thur.e <- sem(mod.cfa.thur.e, R.thur, 213) summary(cfa.thur.e) # (3) in path format: mod.cfa.thur.p <- specifyModel(covs="F1, F2, F3") F1 -> Sentences, lam11 F1 -> Vocabulary, lam21 F1 -> Sent.Completion, lam31 F2 -> First.Letters, lam41 F2 -> 4.Letter.Words, lam52 F2 -> Suffixes, lam62 F3 -> Letter.Series, lam73 F3 -> Pedigrees, lam83 F3 -> Letter.Group, lam93 F1 <-> F1, NA, 1 F2 <-> F2, NA, 1 F3 <-> F3, NA, 1 cfa.thur.p <- sem(mod.cfa.thur.p, R.thur, 213) summary(cfa.thur.p) # The Thursstone CFA model with equality constraints on the # factor loadings and error variances mod.cfa.thur.ceq <- cfa(reference.indicators=FALSE) FA: Sentences = Vocabulary = Sent.Completion FB: First.Letters = 4.Letter.Words = Suffixes FC: Letter.Series = Pedigrees = Letter.Group var: Sentences = Vocabulary = Sent.Completion var: First.Letters = 4.Letter.Words = Suffixes var: Letter.Series = Pedigrees = Letter.Group cfa.thur.ceq <- sem(mod.cfa.thur.ceq, R.thur, 213) summary(cfa.thur.ceq) anova(cfa.thur.c, cfa.thur.ceq) pathDiagram(cfa.thur.ceq, ignore.double=FALSE, ignore.self=TRUE, min.rank="FA, FB, FC", edge.labels="values") # a multigroup CFA model fit to the Holzinger-Swineford # mental-tests data mod.hs <- cfa() spatial: visual, cubes, paper, flags verbal: general, paragrap, sentence, wordc, wordm memory: wordr, numberr, figurer, object, numberf, figurew math: deduct, numeric, problemr, series, arithmet mod.mg <- multigroupModel(mod.hs, groups=c("Female", "Male")) sem.mg <- sem(mod.mg, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg) # with cross-group equality constraints: mod.mg.eq <- multigroupModel(mod.hs, groups=c("Female", "Male"), allEqual=TRUE) sem.mg.eq <- sem(mod.mg.eq, data=HS.data, group="Gender", formula = ~ visual + cubes + paper + flags + general + paragrap + sentence + wordc + wordm + wordr + numberr + figurer + object + numberf + figurew + deduct + numeric + problemr + series + arithmet ) summary(sem.mg.eq) ## End(Not run)
These functions calculate standardized regression coefficients
for structural equation models. The function stdCoef
is
simply an abbreviation for standardizedCoefficients
.
standardizedCoefficients(object, ...) ## S3 method for class 'sem' standardizedCoefficients(object, digits = getOption("digits"), oneheaded = TRUE, twoheaded = TRUE, ...) ## S3 method for class 'msem' standardizedCoefficients(object, ...) stdCoef(...)
standardizedCoefficients(object, ...) ## S3 method for class 'sem' standardizedCoefficients(object, digits = getOption("digits"), oneheaded = TRUE, twoheaded = TRUE, ...) ## S3 method for class 'msem' standardizedCoefficients(object, ...) stdCoef(...)
object |
an object of class |
digits |
number of digits for printed output. |
oneheaded |
standardize path coefficients? Default is |
twoheaded |
standardize variances and covariances? Default is |
... |
arguments to pass down. |
Returns a data frame with the coefficients, labelled
both by parameter names and by arrows in the path diagram for the
model. The msem
(multigroup) method computes and prints the
standardized coefficients for each group; it does not return a useful result.
John Fox [email protected] and Adam Kramer
Bollen, K. A. (1989) Structural Equations With Latent Variables. Wiley.
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # Duncan, Haller, and Portes peer-influences model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) standardizedCoefficients(sem.dhp) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) (sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp'))) standardizedCoefficients(sem.dhp)
# In the first example, readMoments() and specifyModel() read from the # input stream. This example cannot be executed via example() but can be entered # at the command prompt. The example is repeated using file input; # this example can be executed via example(). ## Not run: # Duncan, Haller, and Portes peer-influences model R.DHP <- readMoments(diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp")) .6247 .3269 .3669 .4216 .3275 .6404 .2137 .2742 .1124 .0839 .4105 .4043 .2903 .2598 .1839 .3240 .4047 .3054 .2786 .0489 .2220 .2930 .2407 .4105 .3607 .0186 .1861 .2707 .2995 .2863 .5191 .5007 .0782 .3355 .2302 .2950 .0760 .0702 .2784 .1988 .1147 .1021 .0931 -.0438 .2087 model.dhp <- specifyModel() RParAsp -> RGenAsp, gam11, NA RIQ -> RGenAsp, gam12, NA RSES -> RGenAsp, gam13, NA FSES -> RGenAsp, gam14, NA RSES -> FGenAsp, gam23, NA FSES -> FGenAsp, gam24, NA FIQ -> FGenAsp, gam25, NA FParAsp -> FGenAsp, gam26, NA FGenAsp -> RGenAsp, beta12, NA RGenAsp -> FGenAsp, beta21, NA RGenAsp -> ROccAsp, NA, 1 RGenAsp -> REdAsp, lam21, NA FGenAsp -> FOccAsp, NA, 1 FGenAsp -> FEdAsp, lam42, NA RGenAsp <-> RGenAsp, ps11, NA FGenAsp <-> FGenAsp, ps22, NA RGenAsp <-> FGenAsp, ps12, NA ROccAsp <-> ROccAsp, theta1, NA REdAsp <-> REdAsp, theta2, NA FOccAsp <-> FOccAsp, theta3, NA FEdAsp <-> FEdAsp, theta4, NA sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp')) standardizedCoefficients(sem.dhp) ## End(Not run) # The following example can be executed via example(): etc <- system.file(package="sem", "etc") # path to data and model files (R.DHP <- readMoments(file=file.path(etc, "R-DHP.txt"), diag=FALSE, names=c("ROccAsp", "REdAsp", "FOccAsp", "FEdAsp", "RParAsp", "RIQ", "RSES", "FSES", "FIQ", "FParAsp"))) (model.dhp <- specifyModel(file=file.path(etc, "model-DHP.txt"))) (sem.dhp <- sem(model.dhp, R.DHP, 329, fixed.x=c('RParAsp', 'RIQ', 'RSES', 'FSES', 'FIQ', 'FParAsp'))) standardizedCoefficients(sem.dhp)
These data are from the SAS manual and consist of six mental tests for 32 students,
with some missing data. The three x
variables are intended to load on a verbal
factor, and the three y
variables on a math factor. The data can be used to
illustrate the estimation of a confirmatory factor analysis model by multinormal full-information
maximum-likelihood in the presence of missing data.
Tests
Tests
A data frame with 32 observations on the following 6 variables.
x1
score on verbal test 1.
x2
score on verbal test 2.
x3
score on verbal test 3.
y1
score on math test 1.
y2
score on math test 2.
y3
score on math test 3.
Example 25.13 from SAS/STAT 9.22 User's Guide, SAS Institute, 2010.
Fits a regression equation, such as an equation in a structural-equation model, by two-stage least squares. This is equivalent to direct instrumental-variables estimation when the number of instruments is equal to the number of predictors.
## S3 method for class 'formula' tsls(formula, instruments, data, subset, weights, na.action, contrasts=NULL, ...) ## Default S3 method: tsls(y, X, Z, w, names=NULL, ...) ## S3 method for class 'tsls' print(x, ...) ## S3 method for class 'tsls' summary(object, digits=getOption("digits"), ...) ## S3 method for class 'summary.tsls' print(x, ...) ## S3 method for class 'tsls' anova(object, model.2, s2, dfe, ...) ## S3 method for class 'tsls' fitted(object, ...) ## S3 method for class 'tsls' residuals(object, ...) ## S3 method for class 'tsls' coef(object, ...) ## S3 method for class 'tsls' vcov(object, ...)
## S3 method for class 'formula' tsls(formula, instruments, data, subset, weights, na.action, contrasts=NULL, ...) ## Default S3 method: tsls(y, X, Z, w, names=NULL, ...) ## S3 method for class 'tsls' print(x, ...) ## S3 method for class 'tsls' summary(object, digits=getOption("digits"), ...) ## S3 method for class 'summary.tsls' print(x, ...) ## S3 method for class 'tsls' anova(object, model.2, s2, dfe, ...) ## S3 method for class 'tsls' fitted(object, ...) ## S3 method for class 'tsls' residuals(object, ...) ## S3 method for class 'tsls' coef(object, ...) ## S3 method for class 'tsls' vcov(object, ...)
formula |
model formula for structural equation to be estimated; a regression constant is implied if not explicitly omitted. |
instruments |
one-sided model formula specifying instrumental variables. |
data |
an optional data frame containing the variables in the model.
By default the variables are taken from the environment from which |
subset |
an optional vector specifying a subset of observations to be used in fitting the model. |
weights , w
|
an optional vector of weights to be used in the fitting process; if specified should be a non-negative numeric vector with one entry for each observation, to be used to compute weighted 2SLS estimates. |
na.action |
a function that indicates what should happen when the
data contain |
contrasts |
an optional list. See the |
y |
Response-variable vector. |
X |
Matrix of predictors, including a constant (if one is in the model). |
Z |
Matrix of instrumental variables, including a constant (if one is in the model). |
names |
optional character vector of names for the columns of the |
x , object , model.2
|
objects of class |
s2 |
an optional estimate of error variance for the denominator of the |
dfe |
optional error degrees of freedom, to be specified when an estimate of error variance is given. |
digits |
number of digits for summary output. |
... |
arguments to be passed down. |
tsls.formula
returns an object of class tsls
, with the following components:
n |
number of observations. |
p |
number of parameters. |
coefficients |
parameter estimates. |
V |
estimated covariance matrix of coefficients. |
s |
residual standard error. |
residuals |
vector of residuals. |
response |
vector of response values. |
X |
model matrix. |
Z |
instrumental-variables matrix. |
response.name |
name of response variable, or expression evaluating to response. |
formula |
model formula. |
instruments |
one-sided formula for instrumental variables. |
John Fox [email protected]
Fox, J. (1979) Simultaneous equation models and two-stage least-squares. In Schuessler, K. F. (ed.) Sociological Methodology 1979, Jossey-Bass.
Greene, W. H. (1993) Econometric Analysis, Second Edition, Macmillan.
summary(tsls(Q ~ P + D, ~ D + F + A, data=Kmenta)) # demand equation summary(tsls(Q ~ P + F + A, ~ D + F + A, data=Kmenta)) # supply equation anova(tsls(Q ~ P + F + A, ~ D + F + A, data=Kmenta), tsls(Q ~ 1, ~ D + F + A, data=Kmenta))
summary(tsls(Q ~ P + D, ~ D + F + A, data=Kmenta)) # demand equation summary(tsls(Q ~ P + F + A, ~ D + F + A, data=Kmenta)) # supply equation anova(tsls(Q ~ P + F + A, ~ D + F + A, data=Kmenta), tsls(Q ~ 1, ~ D + F + A, data=Kmenta))