### Inspect lavaan Fit Object Starting Values (R) Source: https://www.lavaan.ugent.be/tutorial/inspect This example demonstrates how to retrieve the starting values for parameters within each model matrix of a fitted lavaan object using the 'start' option of the lavInspect function. This is useful for understanding the initial parameter estimates before optimization. ```r lavInspect(fit, what = "start") ``` -------------------------------- ### Load and Verify lavaan Library Installation Source: https://www.lavaan.ugent.be/tutorial/install Loads the lavaan library into the R environment and displays the version information. This command verifies that the installation was successful and displays the startup message with the current version number and license information. ```r library(lavaan) ``` -------------------------------- ### Expected lavaan Startup Message Output Source: https://www.lavaan.ugent.be/tutorial/install The console output displayed after successfully loading the lavaan library, indicating version 0.6-20 and confirming that lavaan is free software. This message verifies proper installation and readiness to use the package. ```r This is lavaan 0.6-20 lavaan is FREE software! Please report any bugs. ``` -------------------------------- ### Provide Custom Starting Values in Lavaan Source: https://www.lavaan.ugent.be/tutorial/syntax2 Explains how to provide custom starting values for free parameters in lavaan models using the `start()` function. The starting value is passed as an argument to `start()`, which then pre-multiplies the corresponding variable in the model syntax. ```r visual =~ x1 + start(0.8)*x2 + start(1.2)*x3 textual =~ x4 + start(0.5)*x5 + start(1.0)*x6 speed =~ x7 + start(0.7)*x8 + start(1.8)*x9 ``` -------------------------------- ### R: Install lavaan Package Source: https://www.lavaan.ugent.be/tutorial/.R Installs the lavaan package from CRAN, including any necessary dependencies. This is the first step to using lavaan for structural equation modeling in R. ```R # install.packages("lavaan", dependencies = TRUE) ``` -------------------------------- ### Fit SEM with Labeled Parameters in lavaan Source: https://www.lavaan.ugent.be/tutorial/.R This example shows how to fit an SEM where parameters are given specific labels (e.g., `b1`, `b2`). This is useful for setting up constraints or interpreting specific pathways. ```R # model <- ' # # latent variable definitions # ind60 =~ x1 + x2 + myLabel*x3 # dem60 =~ y1 + y2 + y3 + y4 # dem65 =~ y5 + y6 + y7 + y8 # # regressions # dem60 ~ ind60 # dem65 ~ ind60 + dem60 # # residual (co)variances # y1 ~~ y5 # y2 ~~ y4 + y6 # y3 ~~ y7 # y4 ~~ y8 # y6 ~~ y8 # ' ``` -------------------------------- ### R: Complete Lavaan Model Syntax Example Source: https://www.lavaan.ugent.be/tutorial/syntax1 Presents a comprehensive lavaan model syntax string enclosed in single quotes, combining regressions, latent variable definitions, variances/covariances, and intercepts. This example demonstrates how to structure a complex model for estimation. ```R myModel <- ' # regressions y1 + y2 ~ f1 + f2 + x1 + x2 f1 ~ f2 + f3 f2 ~ f3 + x1 + x2 # latent variable definitions f1 =~ y1 + y2 + y3 f2 =~ y4 + y5 + y6 f3 =~ y7 + y8 + y9 + y10 # variances and covariances y1 ~~ y1 y1 ~~ y2 f1 ~~ f2 # intercepts y1 ~ 1 f1 ~ 1 ' ``` -------------------------------- ### Install lavaan Package from CRAN Source: https://www.lavaan.ugent.be/tutorial/install Installs the lavaan package and its dependencies from CRAN repository. This is the primary installation method for obtaining the lavaan statistical package used for latent variable modeling and structural equation modeling in R. ```r install.packages("lavaan", dependencies = TRUE) ``` -------------------------------- ### R: Load lavaan Package Source: https://www.lavaan.ugent.be/tutorial/.R Loads the lavaan package into the current R session, making its functions available for use. This command is essential after installing the package. ```R library(lavaan) ``` -------------------------------- ### R: Inspect Initial Model State in lavaan Source: https://www.lavaan.ugent.be/tutorial/.R Retrieves the starting values used for model estimation in lavaan. This can be useful for debugging or understanding the optimization process. ```R lavInspect(fit, what = "start") ``` -------------------------------- ### Fit SEM with Parameter Constraints in lavaan Source: https://www.lavaan.ugent.be/tutorial/.R This snippet demonstrates how to define and fit an SEM with specific constraints on the parameters. The constraints are defined as additional lines in the model syntax, using operators like `==` and `>`. A dataset is also generated for this example. ```R set.seed(1234) Data <- data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100), x3 = rnorm(100)) model <- ' y ~ b1*x1 + b2*x2 + b3*x3 ' fit <- sem(model, data = Data) coef(fit) # model.constr <- ' # model with labeled parameters # y ~ b1*x1 + b2*x2 + b3*x3 # # constraints # b1 == (b2 + b3)^2 # b1 > exp(b2 + b3) ' ``` -------------------------------- ### Fit and Summarize SEM Model in R using Lavaan Source: https://www.lavaan.ugent.be/tutorial/sem Fits a structural equation model using the `sem` function from the lavaan package and then prints a detailed summary of the results, including standardized estimates. Requires the `model` syntax and the `PoliticalDemocracy` dataset. ```r fit <- sem(model, data = PoliticalDemocracy) summary(fit, standardized = TRUE) ``` -------------------------------- ### Fit CFA Model with lavaan in R Source: https://www.lavaan.ugent.be/tutorial/cfa This R code fits a confirmatory factor analysis model using the `cfa()` function from the lavaan package. It takes the model syntax and the dataset as input. The `HolzingerSwineford1939` dataset is a built-in dataset in lavaan, commonly used for SEM examples. ```R fit <- cfa(HS.model, data = HolzingerSwineford1939) ``` -------------------------------- ### Loading Data for ESEM Example in lavaan Source: https://www.lavaan.ugent.be/tutorial/efa Reads data from a URL into an R data frame for use in the ESEM example. Assigns names 'y1' through 'y12' to the columns of the loaded data. ```R ex5_25 <- read.table("http://statmodel.com/usersguide/chap5/ex5.25.dat") names(ex5_25) = paste0("y",1:12) ``` -------------------------------- ### R: Lavaan Model with Latent Variables Source: https://www.lavaan.ugent.be/tutorial/syntax1 Illustrates a lavaan model syntax with multiple regression formulas involving both observed and latent variables. Latent variables are indicated by names starting with 'f'. ```R y ~ f1 + f2 + x1 + x2 f1 ~ f2 + f3 f2 ~ f3 + x1 + x2 ``` -------------------------------- ### R: Fit Confirmatory Factor Analysis Model with lavaan Source: https://www.lavaan.ugent.be/tutorial/cfa This code snippet demonstrates how to fit a three-factor confirmatory factor analysis (CFA) model using the lavaan package in R. It includes loading the package, specifying the model syntax, and fitting the model to a dataset. ```r library(lavaan) # specify the model HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' # fit the model fit <- cfa(HS.model, data = HolzingerSwineford1939) ``` -------------------------------- ### Summarize CFA Model Results in R Source: https://www.lavaan.ugent.be/tutorial/cfa This R code displays a comprehensive summary of the fitted CFA model. The `summary()` function provides detailed output including model fit measures, parameter estimates, and standard errors. `fit.measures = TRUE` requests additional fit indices. ```R summary(fit, fit.measures = TRUE) ``` -------------------------------- ### Specify and Fit Structural Equation Model with lavaan Source: https://www.lavaan.ugent.be/tutorial/sem This R code snippet demonstrates how to define a structural equation model using the `lavaan` package. It includes specifying the measurement model with latent variables and their indicators, defining regression paths between latent variables, and setting up residual correlations. The `sem()` function is then used to fit this model to the provided data, followed by generating a summary of the fit, including standardized parameter estimates. ```r library(lavaan) # only needed once per session model <- ' # measurement model ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 # regressions dem60 ~ ind60 dem65 ~ ind60 + dem60 # residual correlations y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' fit <- sem(model, data=PoliticalDemocracy) summary(fit, standardized=TRUE) ``` -------------------------------- ### Fit SEM with rotation using lavaan in R Source: https://www.lavaan.ugent.be/tutorial/.R This snippet shows how to fit a structural equation model using the `sem` function, specifying a rotation method ('geomin'). It's commented out, indicating it's an example of how to perform this analysis. Requires the lavaan package. ```r # fit <- sem(model = model, data = myData, rotation = "geomin") ``` -------------------------------- ### Define SEM Model Syntax in R using Lavaan Source: https://www.lavaan.ugent.be/tutorial/sem Specifies a structural equation model using lavaan's syntax. This includes defining latent variables with `=~`, regressions with `~`, and residual correlations with `~~`. The syntax is stored in a character string. ```r model <- ' # measurement model ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 # regressions dem60 ~ ind60 dem65 ~ ind60 + dem60 # residual correlations y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' ``` -------------------------------- ### Fit Confirmatory Factor Analysis Model in R lavaan Source: https://www.lavaan.ugent.be/tutorial/cfa This code illustrates the basic usage of the `cfa()` function from the lavaan package to fit a confirmatory factor analysis model. It requires a lavaan model syntax string and a dataset containing the observed variables. The output is a fitted model object. ```r fit <- cfa(model, data = my_data) ``` -------------------------------- ### lavaan Model Summary Output for Multiple Groups Source: https://www.lavaan.ugent.be/tutorial/groups Displays the summary of a fitted lavaan model, including model test statistics and parameter estimates for each group. This output is crucial for verifying the effects of specified fixed parameters and starting values. ```R lavaan 0.6-20 ended normally after 45 iterations Estimator ML Optimization method NLMINB Number of model parameters 56 Number of observations per group: Pasteur 156 Grant-White 145 Model Test User Model: Test statistic 118.976 Degrees of freedom 52 P-value (Chi-square) 0.000 Test statistic for each group: Pasteur 64.901 Grant-White 54.075 Parameter Estimates: Standard errors Standard Information Expected Information saturated (h1) model Structured Group 1 [Pasteur]: Latent Variables: Estimate Std.Err z-value P(>|z|) visual =~ x1 1.000 x2 0.500 x3 0.600 textual =~ x4 1.000 x5 1.185 0.102 11.598 0.000 x6 (a1) 0.876 0.077 11.409 0.000 speed =~ x7 1.000 x8 1.129 0.279 4.055 0.000 x9 0.931 0.227 4.103 0.000 Covariances: Estimate Std.Err z-value P(>|z|) visual ~~ ``` -------------------------------- ### lavaan Model Definition with Group-Specific Parameters Source: https://www.lavaan.ugent.be/tutorial/groups Defines a structural equation model in lavaan, specifying fixed factor loadings and starting values for indicators across different groups. It demonstrates how to apply group-specific constraints using vectors and labels for parameters. ```R HS.model <- ' visual =~ x1 + 0.5*x2 + c(0.6, 0.8)*x3 textual =~ x4 + start(c(1.2, 0.6))*x5 + c(a1, a2)*x6 speed =~ x7 + x8 + x9 ' fit <- cfa(HS.model, data = HolzingerSwineford1939, group = "school") summary(fit) ``` -------------------------------- ### R: Confirmatory Factor Analysis (CFA) Model Specification with lavaan Source: https://www.lavaan.ugent.be/tutorial/.R Specifies a confirmatory factor analysis model using lavaan syntax. This model defines three latent factors (visual, textual, speed) and their respective observed variables. It's a common setup for scale reliability and structure analysis. ```R library(lavaan) HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' ``` -------------------------------- ### CFA Model Specification Source: https://www.lavaan.ugent.be/tutorial/cfa This code snippet shows the core R syntax for defining a confirmatory factor analysis model. It uses the lavaan package's specific syntax where latent variables are defined with their indicator variables using the '=~' operator. ```R visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ``` -------------------------------- ### R: Get Modification Indices with lavaan Source: https://www.lavaan.ugent.be/tutorial/.R Calculates and displays modification indices for a fitted lavaan model. Modification indices suggest which paths, if added to the model, would most improve the model fit, guiding model respecification. ```R fit <- cfa(HS.model, data = HolzingerSwineford1939) modindices(fit, sort = TRUE, maximum.number = 5) ``` -------------------------------- ### Load and fit a CFA model with lavaan in R Source: https://www.lavaan.ugent.be/tutorial/.R This snippet shows the complete process of loading the lavaan package, specifying a CFA model, fitting it to data, and displaying the summary output. It is intended for use within an R session. ```r # load the lavaan package (only needed once per session) library(lavaan) # specify the model HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' # fit the model fit <- cfa(HS.model, data = HolzingerSwineford1939) # display summary output summary(fit, fit.measures = TRUE) ``` -------------------------------- ### Lavaan: Accessing Options and Help in R Source: https://www.lavaan.ugent.be/tutorial/est This command provides instructions on how to access the help documentation for lavaan options in R. Typing '?lavOptions' in the R console will display detailed information about available options for customizing lavaan analyses. ```r ?lavOptions ``` -------------------------------- ### Access lavInspect Help Page (R) Source: https://www.lavaan.ugent.be/tutorial/inspect This command provides access to the help documentation for the lavInspect function in the lavaan package. It is recommended to consult the help page for a comprehensive understanding of all available options and their functionalities. ```r ?lavInspect ``` -------------------------------- ### R: Splitting Lavaan Model Syntax Source: https://www.lavaan.ugent.be/tutorial/syntax1 Illustrates how to split a lavaan model syntax into multiple parts, which can be useful for managing complex models or for specific estimation strategies. Each part is defined as a separate string. ```R part1 <- ' # latent variable definitions f1 =~ y1 + y2 + y3 f2 =~ y4 + y5 + y6 f3 =~ y7 + y8 + y9 + y10 ' part2 <- ' # fix covariance between f1 and f2 to zero f1 ~~ 0*f2 ' ``` -------------------------------- ### Lavaan: Displaying Estimation Results in R Source: https://www.lavaan.ugent.be/tutorial/est This output shows the results of a lavaan model fit, detailing the estimator used (ML), optimization method, number of parameters, and observations. It also presents the model test results, including the chi-square test statistic, degrees of freedom, and p-value. ```r lavaan 0.6-20 ended normally after 35 iterations Estimator ML Optimization method NLMINB Number of model parameters 21 Number of observations 301 Model Test User Model: Test statistic 85.022 Degrees of freedom 24 P-value (Chi-square) 0.000 ``` -------------------------------- ### Get Standardized Solution Estimates - lavaan R Source: https://www.lavaan.ugent.be/tutorial/inspect The standardizedSolution() function provides standardized parameter estimates and their associated statistics from a fitted lavaan model. This is useful for interpreting effect sizes. ```R fit <- cfa(HS.model, data=HolzingerSwineford1939) standardizedSolution(fit) ``` -------------------------------- ### ESEM Model Syntax with EFA and CFA Blocks in lavaan Source: https://www.lavaan.ugent.be/tutorial/efa Defines an ESEM model with a single EFA block ('efa1' for f1, f2) and a single CFA block (for f3, f4), including regressions. This syntax is used for Mplus example 5.25. ```R model <-ടെ'\n # efa block efa("efa1")*f1 + efa("efa1")*f2 =~ y1 + y2 + y3 + y4 + y5 + y6 # cfa block f3 =~ y7 + y8 + y9 f4 =~ y10 + y11 + y12 # regressions f3 ~ f1 + f2 f4 ~ f3 '__ ``` -------------------------------- ### Define and Visualize SEM Model with semPlot and qgraph in R Source: https://www.lavaan.ugent.be/tutorial/.R This code defines a structural equation model with measurement and regression paths, then fits it to the 'PoliticalDemocracy' dataset. It subsequently uses semPaths to generate a graph object representing the model and qgraph to visualize it with a custom layout. ```R library(lavaan) library(semPlot) library(qgraph) model <- ' # measurement model ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 # regressions dem60 ~ ind60 dem65 ~ ind60 + dem60 # residual correlations y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' fit <- sem(model, data=PoliticalDemocracy) Graph <- semPaths(fit, layout="tree2", nCharNodes=0, curve=1, rotation=4, edge.color="black", border.width=1.0, esize=1.0, label.scale=FALSE, label.cex=1.0, residuals=FALSE, fixedStyle=1, freeStyle=1, curvePivot=FALSE,exoVar=FALSE, sizeMan=7, sizeLat=10, DoNotPlot=FALSE ) L <- matrix(c( 0.4 , 1 , 0.7 , 1 , 1.0 , 1 , -1.0 , 1 , -1.0 , 0.71 , -1.0 , 0.43 , -1.0 , 0.14 , -1.0 , -0.14 , -1.0 , -0.43 , -1.0 , -0.71 , -1.0 , -1 , 0.7 , 0.4 , 0.0 , 0.4 , 0.0 , -0.4 ), 14,2, byrow=TRUE) qgraph(Graph, layout=L, arrowAngle=0.5) ``` -------------------------------- ### Create Toy Dataset and Fit Regression Model in lavaan Source: https://www.lavaan.ugent.be/tutorial/syntax2 Generates a toy dataset with four variables (y, x1, x2, x3) using random normal distributions and fits a regression model with explicitly labeled coefficients. The coef() function extracts the estimated parameter values from the fitted model. ```R set.seed(1234) Data <- data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100), x3 = rnorm(100)) model <- ' y ~ b1*x1 + b2*x2 + b3*x3 ' fit <- sem(model, data = Data) coef(fit) ``` -------------------------------- ### R: Get Residuals from lavaan Fit Source: https://www.lavaan.ugent.be/tutorial/.R Calculates and returns the residuals from a fitted lavaan model. Residuals represent the discrepancies between the observed covariance matrix and the covariance matrix implied by the model, helping to identify areas where the model does not fit well. ```R resid(fit) ``` -------------------------------- ### Load data and define a mixed EFA/CFA model in R Source: https://www.lavaan.ugent.be/tutorial/.R This code first loads data from a URL into a data frame and names the columns. Then, it defines a model that combines exploratory factor analysis (EFA) and confirmatory factor analysis (CFA) blocks, along with regression paths. Requires the lavaan package. ```r ex5_25 <- read.table("http://statmodel.com/usersguide/chap5/ex5.25.dat") names(ex5_25) = paste0("y",1:12) model <- ' # efa block efa("efa1")*f1 + efa("efa1")*f2 =~ y1 + y2 + y3 + y4 + y5 + y6 # cfa block f3 =~ y7 + y8 + y9 f4 =~ y10 + y11 + y12 # regressions f3 ~ f1 + f2 f4 ~ f3 ' ``` -------------------------------- ### R: Get Fitted Model Information with lavaan Source: https://www.lavaan.ugent.be/tutorial/.R Extracts information about the fitted model from a lavaan object. This function provides details on model convergence, parameter estimates, and other relevant statistics, useful for assessing the overall fit and interpretation of the model. ```R fitted(fit) ``` -------------------------------- ### Apply Parameter Constraints to SEM in lavaan Source: https://www.lavaan.ugent.be/tutorial/.R This code fits an SEM model with predefined parameter constraints. The `model.constr` object defines the model structure, parameter labels, and the specific equality and inequality constraints to be applied during model fitting. ```R model.constr <- ' # model with labeled parameters y ~ b1*x1 + b2*x2 + b3*x3 # constraints b1 == (b2 + b3)^2 b1 > exp(b2 + b3) ' fit <- sem(model.constr, data = Data) coef(fit) ``` -------------------------------- ### R: Get Parameter Estimates from lavaan Fit Source: https://www.lavaan.ugent.be/tutorial/.R Retrieves the parameter estimates from a fitted lavaan model object. This includes factor loadings, intercepts, and variances, providing insight into the model's structure and the relationships between latent and observed variables. ```R parameterEstimates(fit) ``` -------------------------------- ### Running Lavaan SEM with EM Optimization Source: https://www.lavaan.ugent.be/tutorial/multilevel Shows how to fit a structural equation model (SEM) using the Lavaan package with the Expectation Maximization (EM) optimization method. This is useful for addressing convergence issues encountered with the default quasi-Newton procedure. ```R fit <- sem(model = model, data = Demo.twolevel, cluster = "cluster", verbose = TRUE, optim.method = "em")__ ``` -------------------------------- ### Fit SEM Model with Geomin Rotation in R Source: https://www.lavaan.ugent.be/tutorial/.R Fits a structural equation model using the sem() function with Geomin rotation. It specifies the model, data, rotation method, and rotation arguments like starting values and algorithm. Dependencies include the lavaan package. ```r library(lavaan) fit <- sem(model = model, data = ex5_25, rotation = "geomin", # mimic Mplus information = "observed", rotation.args = list(rstarts = 30, row.weights = "none", algorithm = "gpa", std.ov = TRUE, geomin.epsilon = 0.0001)) summary(fit) ``` -------------------------------- ### Nonlinear Equality and Inequality Constraints in lavaan Source: https://www.lavaan.ugent.be/tutorial/syntax2 Defines a regression model with labeled coefficients and applies nonlinear constraints using == for equality (b1=(b2+b3)^2) and > for inequality (b1>exp(b2+b3)). The constraints section uses mathematical expressions to relate multiple parameters. ```R model.constr <- ' # model with labeled parameters y ~ b1*x1 + b2*x2 + b3*x3 # constraints b1 == (b2 + b3)^2 b1 > exp(b2 + b3) ' ``` -------------------------------- ### Inspect lavaan Fit Object Parameter List (R) Source: https://www.lavaan.ugent.be/tutorial/inspect This code snippet illustrates how to use lavInspect with the 'list' option to obtain a detailed representation of how lavaan internally represents the model. The output is equivalent to the parTable function and is often referred to as the 'parameter table'. ```r lavInspect(fit, what = "list") ``` -------------------------------- ### Fit and Summarize SEM Model in R Source: https://www.lavaan.ugent.be/tutorial/.R This snippet shows a concise way to fit a structural equation model defined by a 'model' object to the 'PoliticalDemocracy' dataset using the `sem` function from the lavaan package. It then prints a standardized summary of the model fit. ```R fit <- sem(model, data = PoliticalDemocracy) summary(fit, standardized = TRUE) ``` -------------------------------- ### Combine Multiple Modifiers for a Parameter in lavaan (R) Source: https://www.lavaan.ugent.be/tutorial/syntax2 Illustrates how to apply multiple modifiers (e.g., custom label and starting value) to a single parameter within a lavaan model formula using a chained notation. This is the recommended approach for combining modifiers. ```R f =~ y1 + y2 + myLabel*start(0.5)*y3 + y4 ``` -------------------------------- ### Simple Equality Constraints with Custom Labels in lavaan Source: https://www.lavaan.ugent.be/tutorial/syntax2 Specifies a three-factor confirmatory factor analysis model where factor loadings of x2 and x3 indicators are constrained to be equal using the same label (v2). Parameters sharing the same label are estimated as a single value and applied to all occurrences. ```R visual =~ x1 + v2*x2 + v2*x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ``` -------------------------------- ### Define Linear Growth Model in Lavaan Source: https://www.lavaan.ugent.be/tutorial/growth Specifies a linear growth model with a random intercept and slope for four time points. The intercept (i) is fixed to represent the starting point, and the slope (s) captures the rate of change over time. This model assumes fixed coefficients for the growth functions. ```R # linear growth model with 4 timepoints # intercept and slope with fixed coefficients i =~ 1*t1 + 1*t2 + 1*t3 + 1*t4 s =~ 0*t1 + 1*t2 + 2*t3 + 3*t4 ``` -------------------------------- ### Define and fit a 3-factor CFA model in R Source: https://www.lavaan.ugent.be/tutorial/.R This code defines a 3-factor CFA model using lavaan syntax and fits it to the HolzingerSwineford1939 dataset. It then visualizes the model using `semPaths`. Dependencies include the lavaan and semPlot packages. ```r library(lavaan) library(semPlot) HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit <- cfa(HS.model, data = HolzingerSwineford1939) semPaths(fit, layout="tree", curve=1, rotation=4, nCharNodes=0, mar=c(3,20,3,20), border.width=1.0, esize=1.0, edge.color="black", label.scale=FALSE, label.cex=1.0, residuals=FALSE, fixedStyle=1, freeStyle=1, curvePivot=FALSE, sizeMan=7, sizeLat=10) ``` -------------------------------- ### Adding Intercepts to H&S CFA Model in Lavaan Source: https://www.lavaan.ugent.be/tutorial/means This example demonstrates how to add intercepts for the observed variables in a three-factor H&S CFA model using Lavaan syntax. It follows the standard 'factor =~ indicators' structure and adds the intercept specification for each factor's observed variables. ```lavaan # three-factor model visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ``` -------------------------------- ### Group CFA Model Fitting in R Source: https://www.lavaan.ugent.be/tutorial/.R Fits a confirmatory factor analysis model across different groups specified by the 'group' argument. The summary provides model fit statistics for each group. Requires the lavaan package. ```r library(lavaan) HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit <- cfa(HS.model, data = HolzingerSwineford1939, group = "school") summary(fit) ``` -------------------------------- ### Define CFA Model Syntax in R Source: https://www.lavaan.ugent.be/tutorial/cfa This R code defines the syntax for a three-factor confirmatory factor analysis model. It specifies the latent variables (visual, textual, speed) and their corresponding observed indicators (x1-x9). The syntax uses the '=~' operator for latent variable definitions. ```R HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' ``` -------------------------------- ### Lavaan Multiple Group Analysis Setup Source: https://www.lavaan.ugent.be/tutorial/cov This section describes how to configure Lavaan for analyses involving multiple groups. It specifies that the `sample.cov` argument should be a list of covariance matrices, one for each group. Similarly, `sample.mean` should be a list of sample means, and `sample.nobs` can be a list or vector of observation counts per group. ```text ## Multiple groups If you have multiple groups, the `sample.cov` argument must be a list containing the sample variance-covariance matrix of each group as a separate element in the list. If a mean structure is needed, the `sample.mean` argument must be a list containing the sample means of each group. Finally, the `sample.nobs` argument can be either a list or an integer vector containing the number of observations for each group. ``` -------------------------------- ### Basic CFA Model Fitting with Wishart Likelihood in R Source: https://www.lavaan.ugent.be/tutorial/.R Fits a basic confirmatory factor analysis model using the cfa() function, specifying the model, data, and setting the likelihood to 'wishart'. The output shows the fitted model object. Requires the lavaan package. ```r library(lavaan) HS.model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' fit <- cfa(HS.model, data = HolzingerSwineford1939, likelihood = "wishart") fit ``` -------------------------------- ### Simple Equality Constraints Using equal() Modifier in lavaan Source: https://www.lavaan.ugent.be/tutorial/syntax2 Alternative approach to impose equality constraints using the equal() modifier function. This method is useful when no custom label has been specified and requires referring to automatically generated parameter labels. ```R visual =~ x1 + x2 + equal("visual=~x2")*x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ``` -------------------------------- ### Fit Confirmatory Factor Analysis (CFA) model in R Source: https://www.lavaan.ugent.be/tutorial/.R This snippet demonstrates how to fit a Confirmatory Factor Analysis (CFA) model using the `cfa` function from the lavaan package. It requires the lavaan package and a data frame. The output is a fitted model object. ```r # fit <- cfa(myModel, data = myData, # ordered = c("item1","item2", # "item3","item4")) ``` -------------------------------- ### lavaan ESEM Model Summary Output Source: https://www.lavaan.ugent.be/tutorial/efa Provides a summary of the fitted ESEM model, including estimator details, optimization method, parameter counts, rotation settings, number of observations, model test results, and parameter estimates for latent variables and regressions. ```text lavaan 0.6-20 ended normally after 35 iterations Estimator ML Optimization method NLMINB Number of model parameters 34 Row rank of the constraints matrix 2 Rotation method GEOMIN OBLIQUE Geomin epsilon 1e-04 Rotation algorithm (rstarts) GPA (30) Standardized metric TRUE Row weights None Number of observations 500 Model Test User Model: Test statistic 51.353 Degrees of freedom 46 P-value (Chi-square) 0.272 Parameter Estimates: Standard errors Standard Information Observed Observed information based on Hessian Latent Variables: Estimate Std.Err z-value P(>|z|) f1 =~ efa1 y1 0.751 0.048 15.621 0.000 y2 0.858 0.042 20.469 0.000 y3 0.736 0.045 16.343 0.000 y4 0.036 0.051 0.712 0.476 y5 -0.028 0.049 -0.564 0.573 y6 0.002 0.003 0.694 0.488 f2 =~ efa1 y1 0.034 0.045 0.758 0.449 y2 -0.002 0.015 -0.151 0.880 y3 -0.008 0.035 -0.219 0.827 y4 0.763 0.050 15.374 0.000 y5 0.810 0.048 16.796 0.000 y6 0.802 0.041 19.467 0.000 f3 =~ y7 1.000 y8 0.894 0.021 41.936 0.000 y9 0.902 0.021 42.479 0.000 f4 =~ y10 1.000 y11 0.734 0.028 26.424 0.000 y12 0.684 0.028 24.405 0.000 Regressions: Estimate Std.Err z-value P(>|z|) f3 ~ f1 0.493 0.058 8.455 0.000 f2 0.721 0.057 12.755 0.000 f4 ~ f3 0.546 0.032 16.975 0.000 Covariances: ``` -------------------------------- ### Exploratory Factor Analysis (EFA) Model Fitting in R Source: https://www.lavaan.ugent.be/tutorial/.R Performs an exploratory factor analysis using the efa() function, fitting models with one to three factors. It selects specific variables for the analysis. The output provides a summary of the fitted EFA models. Requires the lavaan package. ```r library(lavaan) var.names <- paste("x", 1:9, sep = "") fit <- efa(data = HolzingerSwineford1939[,var.names], nfactors = 1:3) summary(fit) ``` -------------------------------- ### Inspect lavaan Fit Object Default Output (R) Source: https://www.lavaan.ugent.be/tutorial/inspect This code snippet shows how to use the lavInspect function with a fitted lavaan object (e.g., from cfa(), sem(), or growth()) to view the default output, which includes the model matrices used internally. The free parameters are represented by non-zero integers. ```r fit <- cfa(HS.model, data=HolzingerSwineford1939) lavInspect(fit) ``` -------------------------------- ### Define and Fit Two-Level SEM Model in R Source: https://www.lavaan.ugent.be/tutorial/.R This snippet demonstrates defining a two-level structural equation model using lavaan syntax. It specifies measurement and structural paths for both level 1 and level 2, then fits the model to a specified dataset with a cluster variable. ```R library(lavaan) model <- ' level: 1 fw =~ y1 + y2 + y3 fw ~ x1 + x2 + x3 level: 2 fb =~ y1 + y2 + y3 fb ~ w1 + w2 ' fit <- sem(model = model, data = Demo.twolevel, cluster = "cluster") summary(fit) lavInspect(fit, "icc") lavInspect(fit, "h1") ``` -------------------------------- ### Multi-level Model Syntax in Lavaan Source: https://www.lavaan.ugent.be/tutorial/multilevel Demonstrates the correct syntax for defining multi-level models in Lavaan, highlighting the use of 'level: X' followed by the model definition for each level. It also shows how to specify a saturated level by including all variances and covariances of endogenous variables. ```R model <- ' level: 1 fw =~ y1 + y2 + y3 fw ~ x1 + x2 + x3 level: 2 y1 ~~ y1 + y2 + y3 y2 ~~ y2 + y3 y3 ~~ y3 '__ ``` -------------------------------- ### Define Latent Variables and Covariances in lavaan Source: https://www.lavaan.ugent.be/tutorial/.R This snippet demonstrates how to define latent variables and their relationships (e.g., fixing covariance to zero) using lavaan's model syntax. It is useful for setting up the structure of a confirmatory factor analysis model. ```R # latent variable definitions # f1 =~ y1 + y2 + y3 # f2 =~ y4 + y5 + y6 # f3 =~ y7 + y8 + y9 + y10 # # fix covariance between f1 and f2 to zero # f1 ~~ 0*f2 ``` -------------------------------- ### Fitting CFA Model with Mean Structure in Lavaan Source: https://www.lavaan.ugent.be/tutorial/means This R code demonstrates fitting a Confirmatory Factor Analysis (CFA) model using the `cfa()` function in the Lavaan package. It specifies the model syntax (`HS.model`), the data (`HolzingerSwineford1939`), and crucially, sets `meanstructure = TRUE` to include intercepts for latent variables (latent means). The `summary()` function is then called with `remove.unused = FALSE` to display all parameters, including those fixed to zero. ```r fit <- cfa(HS.model, data = HolzingerSwineford1939, meanstructure = TRUE) summary(fit, remove.unused = FALSE) ``` -------------------------------- ### Confirmatory Factor Analysis (CFA) Model Specification and Fitting in R Source: https://www.lavaan.ugent.be/tutorial/.R Defines and fits a CFA model using the cfa() function. The model specifies latent variables and their indicator variables. It also generates standardized output for the fitted model. Requires the lavaan package. ```r library(lavaan) efa.model <- '\n efa("efa")*f1 + \n efa("efa")*f2 + \n efa("efa")*f3 =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9\n' fit <- cfa(efa.model, data = HolzingerSwineford1939) summary(fit, standardized = TRUE) ``` -------------------------------- ### Define lavaan Model and Extract Coefficients (R) Source: https://www.lavaan.ugent.be/tutorial/syntax2 Defines a structural equation model using lavaan syntax and then extracts the estimated coefficients of the free parameters. The output shows parameter names derived from the model formula components (LHS, operator, RHS) and their estimated values. ```R model <- ' # latent variable definitions ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 # regressions dem60 ~ ind60 dem65 ~ ind60 + dem60 # residual (co)variances y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' fit <- sem(model, data = PoliticalDemocracy) coef(fit) ```