### Export SEM Models to lavaan or sem Syntax using semSyntax Source: https://context7.com/sachaepskamp/semplot/llms.txt Illustrates how to convert a fitted lavaan or sem model object into syntax strings for either lavaan or the sem package. This function is useful for model re-specification, sharing, or creating reproducible model definitions. It also shows how to export syntax to a file and fix all parameters. ```r library(semPlot) library(lavaan) # Assume HolzingerSwineford1939 dataset is available # Load it if necessary: data(HolzingerSwineford1939) # Define a CFA model model <- ' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 visual ~~ textual visual ~~ speed textual ~~ speed ' # Fit the model fit <- cfa(model, data = HolzingerSwineford1939) # Convert to lavaan syntax string lavaan_syntax <- semSyntax(fit, syntax = "lavaan") print(lavaan_syntax) # Re-fit using the extracted lavaan syntax fit2 <- cfa(lavaan_syntax, data = HolzingerSwineford1939) # Convert to sem package syntax sem_syntax <- semSyntax(fit, syntax = "sem") print(sem_syntax) # Export syntax with all parameters fixed fixed_syntax <- semSyntax(fit, syntax = "lavaan", allFixed = TRUE) # Save syntax to a file semSyntax(fit, syntax = "lavaan", file = "model_syntax.txt") ``` -------------------------------- ### Create and Visualize SEM Model from Matrices (R) Source: https://context7.com/sachaepskamp/semplot/llms.txt Demonstrates how to define a Structural Equation Model (SEM) using matrices (A, S, F) and then visualize it using semPaths. It covers both basic models and models with mean structures (intercepts). ```r # A matrix: directed paths (regressions and factor loadings) # Rows = to, Columns = from A <- matrix(0, 5, 5) rownames(A) <- colnames(A) <- c("x1", "x2", "x3", "f1", "f2") A["x1", "f1"] <- 0.8 # Factor loading A["x2", "f1"] <- 0.7 A["x3", "f2"] <- 0.9 A["f2", "f1"] <- 0.5 # Structural path # S matrix: symmetric paths (variances and covariances) S <- diag(5) rownames(S) <- colnames(S) <- c("x1", "x2", "x3", "f1", "f2") S["x1", "x1"] <- 0.36 # Residual variances S["x2", "x2"] <- 0.51 S["x3", "x3"] <- 0.19 S["f1", "f1"] <- 1.0 # Latent variance S["f2", "f2"] <- 0.75 # F matrix: filter matrix selecting manifest variables F_mat <- cbind(diag(3), matrix(0, 3, 2)) rownames(F_mat) <- c("x1", "x2", "x3") colnames(F_mat) <- c("x1", "x2", "x3", "f1", "f2") # Create semPlotModel from matrices model <- ramModel(A = A, S = S, F = F_mat, manNames = c("x1", "x2", "x3"), latNames = c("f1", "f2")) # Visualize the model semPaths(model, what = "est", layout = "tree", edge.label.cex = 1, sizeMan = 8, sizeLat = 12) # With meanstructure (intercepts) M <- c(0, 0, 0, 0, 0) # Means vector names(M) <- c("x1", "x2", "x3", "f1", "f2") model_means <- ramModel(A = A, S = S, F = F_mat, M = M, manNames = c("x1", "x2", "x3"), latNames = c("f1", "f2")) semPaths(model_means, intercepts = TRUE) ``` -------------------------------- ### Extract Model Matrices (modelMatrices) (R) Source: https://context7.com/sachaepskamp/semplot/llms.txt Extracts model parameters from a fitted SEM object into different matrix formats (RAM, LISREL, Mplus). This facilitates custom analysis and data export. Requires 'lavaan' for fitting models. ```r library(semPlot) library(lavaan) # Fit a model model <- ' # Measurement eta1 =~ y1 + y2 + y3 eta2 =~ y4 + y5 + y6 xi1 =~ x1 + x2 + x3 # Structural eta1 ~ xi1 eta2 ~ eta1 + xi1 ' fit <- sem(model, data = PoliticalDemocracy) # Extract as RAM matrices (A, S, F) ram <- modelMatrices(fit, model = "ram") names(ram) # [1] "A" "S" "F" ram$A # Asymmetric paths matrix ram$S # Symmetric paths matrix ram$F # Filter matrix # Extract as LISREL matrices lisrel <- modelMatrices(fit, model = "lisrel") names(lisrel) # [1] "LY" "TE" "PS" "BE" "LX" "TD" "PH" "GA" "TY" "TX" "AL" "KA" lisrel$LY # Lambda-Y (endogenous factor loadings) lisrel$BE # Beta (structural paths among endogenous) lisrel$GA # Gamma (paths from exogenous to endogenous) lisrel$PH # Phi (exogenous latent covariances) # Extract as Mplus matrices mplus <- modelMatrices(fit, model = "mplus") names(mplus) # [1] "Nu" "Lambda" "Theta" "Kappa" "Alpha" "Beta" "Gamma" "Psi" # Each matrix contains est, std, fixed, and par elements ram$A[[1]]$est # Parameter estimates ram$A[[1]]$std # Standardized estimates ram$A[[1]]$fixed # Fixed parameter indicators ram$A[[1]]$par # Parameter numbers ``` -------------------------------- ### Calculate Total and Implied Covariance Matrices using semMatrixAlgebra Source: https://context7.com/sachaepskamp/semplot/llms.txt Demonstrates how to use the semMatrixAlgebra function to compute total effects and model-implied covariance matrices from a fitted SEM model. It shows calculations for standardized effects and uses both RAM and LISREL notations for covariance. ```r library(lavaan) # Define a mediation model model <- ' M ~ a*X Y ~ b*M + c*X # Indirect effect indirect := a*b # Total effect total := c + (a*b) ' set.seed(456) X <- rnorm(200) M <- 0.5*X + rnorm(200) Y <- 0.7*M + 0.3*X + rnorm(200) data <- data.frame(X = X, M = M, Y = Y) # Fit the SEM model fit <- sem(model, data = data) # Compute total effects using RAM notation totalEffects <- semMatrixAlgebra(fit, algebra = F %*% solve(diag(nrow(A)) - A), model = "ram") print(totalEffects) # Compute model-implied covariance using RAM notation impliedCov <- semMatrixAlgebra(fit, algebra = F %*% solve(diag(nrow(A)) - A) %*% S %*% t(solve(diag(nrow(A)) - A)) %*% t(F), model = "ram") print(impliedCov) # Compute implied covariance using LISREL notation lisrelCov <- semMatrixAlgebra(fit, algebra = solve(diag(nrow(BE)) - BE) %*% (GA %*% PH %*% t(GA) + PS) %*% t(solve(diag(nrow(BE)) - BE)), model = "lisrel") print(lisrelCov) ``` -------------------------------- ### Visualize Correlation Matrices Comparison (semCors) (R) Source: https://context7.com/sachaepskamp/semplot/llms.txt Compares observed, model-implied, and residual correlation matrices using network visualizations. Useful for model fit assessment and identifying discrepancies. Requires 'lavaan' for fitting models. ```r library(semPlot) library(lavaan) # Fit a factor model model <- ' factor1 =~ item1 + item2 + item3 + item4 factor2 =~ item5 + item6 + item7 + item8 ' # Simulate data for demonstration set.seed(123) data <- simulateData(model, sample.nobs = 300) fit <- cfa(model, data = data) # Visualize observed and implied correlations side by side semCors(fit, include = c("observed", "expected"), vertical = FALSE, # Horizontal layout titles = TRUE, # Show titles layout = "spring", # Layout algorithm maximum = 1, # Maximum edge weight edge.labels = FALSE, # Hide edge labels vsize = 8, # Node size esize = 10) # Edge width scaling # Show all three: observed, expected, and residuals semCors(fit, include = c("observed", "expected", "difference"), vertical = TRUE, # Stack vertically titles = TRUE, groups = "default", # Color scheme layout = "circle") # Circular layout # Focus on residual correlations only semCors(fit, include = "difference", maximum = 0.1, # Scale for residuals cut = 0.05, # Only show |r| > 0.05 legend = TRUE, negCol = "red", posCol = "blue") ``` -------------------------------- ### Create SEM Models from RAM Matrices with ramModel in R Source: https://context7.com/sachaepskamp/semplot/llms.txt The `ramModel` function constructs a `semPlotModel` object directly from RAM (Reticular Action Model) specification matrices: A (asymmetric paths), S (symmetric paths), F (filter matrix), and optionally M (means). This function is useful for manual model specification or integration with custom SEM implementations. ```r library(semPlot) # Define a simple two-factor model with 6 indicators # Variables: x1, x2, x3 (manifest), f1, f2 (latent) ``` -------------------------------- ### Perform Matrix Algebra on SEM Models (semMatrixAlgebra) (R) Source: https://context7.com/sachaepskamp/semplot/llms.txt Enables matrix algebra operations on SEM model matrices (RAM, LISREL, Mplus) to compute derived quantities like total effects or model-implied covariances. Requires 'lavaan' for fitting models. ```r library(semPlot) library(lavaan) ``` -------------------------------- ### Convert SEM Models to Internal Representation with semPlotModel in R Source: https://context7.com/sachaepskamp/semplot/llms.txt The `semPlotModel` function converts SEM model objects from various packages into the standardized `semPlotModel` S4 class. This internal representation unifies parameters, variables, thresholds, and covariance information, facilitating further visualization and analysis. The output can be inspected using `str` and accessing its slots like `@Pars` and `@Vars`. ```r library(semPlot) library(lavaan) # Fit a structural model model <- ' # Measurement model ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 # Structural model dem60 ~ ind60 dem65 ~ ind60 + dem60 ' fit <- sem(model, data = PoliticalDemocracy) # Convert to semPlotModel semModel <- semPlotModel(fit) # Inspect the internal structure str(semModel) # Access parameter estimates head(semModel@Pars) # label lhs edge rhs est std group fixed par # 1 x1 ind60 -> x1 1.000 0.670 1 TRUE 0 # 2 x2 ind60 -> x2 2.180 0.732 1 FALSE 1 # 3 x3 ind60 -> x3 1.819 0.678 1 FALSE 2 # Access variable information semModel@Vars # name manifest exogenous # 1 x1 TRUE NA # 2 x2 TRUE NA # 3 x3 TRUE NA # 4 y1 TRUE NA # ... # Check if model has been computed semModel@Computed # [1] TRUE # Access implied covariance matrix semModel@ImpCovs[[1]] ``` -------------------------------- ### Create Path Diagrams with semPaths in R Source: https://context7.com/sachaepskamp/semplot/llms.txt The `semPaths` function generates path diagrams from SEM model objects. It supports various customization options for layout, styling, labels, and display of parameter estimates, intercepts, and residuals. The function automatically detects model types and converts them for visualization. ```r library(semPlot) library(lavaan) # Define a simple CFA model model <- ' # Latent variable definitions visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 ' # Fit the model fit <- cfa(model, data = HolzingerSwineford1939) # Basic path diagram with default settings semPaths(fit) # Customized path diagram with standardized estimates semPaths(fit, what = "std", # Show standardized estimates whatLabels = "std", # Label edges with standardized values layout = "tree2", # Use tree layout algorithm rotation = 2, # Rotate diagram 90 degrees sizeMan = 7, # Size of manifest variables sizeLat = 10, # Size of latent variables edge.label.cex = 0.8, # Edge label size style = "lisrel", # Use LISREL style intercepts = FALSE, # Hide intercepts residuals = TRUE, # Show residuals nCharNodes = 0, # Don't abbreviate node names nCharEdges = 0, # Don't abbreviate edge labels title = TRUE, # Show title curve = 2) # Curve covariances # Path diagram with custom colors by groups semPaths(fit, what = "paths", whatLabels = "est", groups = "latents", # Color by latent variables pastel = TRUE, # Use pastel colors edge.color = "black", # Black edges layout = "spring") # Spring layout ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.