### Initialize starting values for an OpenMx mixture model Source: https://cjvanlissa.github.io/tidySEM/reference/mixture_starts.html Demonstrates the usage of mixture_starts to set starting values for a 2-class mixture model. This example is wrapped in a conditional check to prevent execution during package checks. ```R if (FALSE) { # \dontrun{ df <- iris[, 1, drop = FALSE] names(df) <- "x" mod <- mx_mixture(model = "x ~ m{C}*1 x ~~ v{C}*x", classes = 2, data = df, run = FALSE) mod <- mixture_starts(mod) } # } ``` -------------------------------- ### Install tidySEM from GitHub Source: https://cjvanlissa.github.io/tidySEM/index.html Installation method for developers or those requiring a specific historical version using the remotes package. ```R install.packages("remotes") remotes::install_github('cjvanlissa/tidySEM') ``` -------------------------------- ### BCH Method Example Source: https://cjvanlissa.github.io/tidySEM/reference/BCH.html Example demonstrating the estimation of an auxiliary model using a latent profile analysis result. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ library(OpenMx) dat <- data.frame(x = iris$Petal.Length) mixmod <- mx_profiles(dat, classes = 2) res <- BCH(mixmod, "y ~ 1", data = data.frame(y = iris$Sepal.Length)) } ``` -------------------------------- ### Install tidySEM from CRAN Source: https://cjvanlissa.github.io/tidySEM/index.html Standard installation method for the public release of the package. ```R install.packages("tidySEM") ``` -------------------------------- ### Run Likelihood Ratio Tests on an OpenMx Model Source: https://cjvanlissa.github.io/tidySEM/reference/lr_test.html This example demonstrates how to use `lr_test` to compare a fitted OpenMx model. Ensure the 'OpenMx' package is installed and loaded. The function performs an overall likelihood ratio test and pairwise comparisons. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ library(OpenMx) df <- iris[c(1:10, 140:150), c(1, 5)] names(df) <- c("x", "group") mod <- as_ram("x~1", data = df, group = "group") mod <- run_mx(mod) lr_test(mod) } ``` -------------------------------- ### Example of estimating a model with Mplus Source: https://cjvanlissa.github.io/tidySEM/reference/estimate_mplus.html Demonstrates initializing a tidy_sem object and running the estimation process. ```R library(MplusAutomation) #> Version: 1.2 #> We work hard to write this free software. Please help us get credit by citing: #> #> Hallquist, M. N. & Wiley, J. F. (2018). MplusAutomation: An R Package for Facilitating Large-Scale Latent Variable Analyses in Mplus. Structural Equation Modeling, 25, 621-638. doi: 10.1080/10705511.2017.1402334. #> #> -- see citation("MplusAutomation"). model <- tidy_sem(iris, "\\.") model <- measurement(model) if (FALSE) { # \dontrun{ estimate_mplus(model, run = 0L) } # } ``` -------------------------------- ### Example of table_fit with mx_mixture Source: https://cjvanlissa.github.io/tidySEM/reference/get_fit.html Demonstrates generating a mixture model and tabulating fit results. Note that this example is wrapped in a dontrun block. ```R if (FALSE) { # \dontrun{ df <- iris[, 1, drop = FALSE] names(df) <- "x" res <- mx_mixture(model = "x ~ m{C}*1 x ~~ v{C}*x", classes = 1, data = df) table_fit(res) } # } ``` -------------------------------- ### Example of as_ram conversion Source: https://cjvanlissa.github.io/tidySEM/reference/as_ram.html Demonstrates converting a simple lavaan regression formula into an OpenMx RAM model. ```R as_ram("y ~ x") ``` -------------------------------- ### Example of as_lavaan conversion Source: https://cjvanlissa.github.io/tidySEM/reference/as_lavaan.html Demonstrates creating a tidy_sem object and converting it to lavaan syntax. ```R mod <- list(syntax = structure(list(lhs = "x", op = "~", rhs = "y", free = TRUE, value = "", label = "", category = "", aspect = ""), class = "data.frame", row.names = c(NA, -1L))) class(mod) <- "tidy_sem" as_lavaan(mod) #> lhs op rhs free value label category aspect #> 1 x ~ y TRUE ``` -------------------------------- ### Install tidySEM development version Source: https://cjvanlissa.github.io/tidySEM/index.html Installation method for accessing the latest features from the R-universe repository. ```R install.packages('tidySEM', repos = c('https://cjvanlissa.r-universe.dev', 'https://cloud.r-project.org')) ``` -------------------------------- ### Example of as_mplus conversion Source: https://cjvanlissa.github.io/tidySEM/reference/as_mplus.html Demonstrates creating a tidy_sem object and converting it to Mplus syntax. ```R mod <- list(syntax = structure(list(lhs = "x", op = "~", rhs = "y", free = TRUE, value = "", label = "", category = "", aspect = ""), class = "data.frame", row.names = c(NA, -1L))) class(mod) <- "tidy_sem" as_mplus(mod) #> [1] "x ON y;" ``` -------------------------------- ### Examples of creating tidy_sem objects Source: https://cjvanlissa.github.io/tidySEM/reference/tidy_sem.html Demonstrates initializing tidy_sem objects with different variable naming conventions and splitting patterns. ```R tidy_sem(c("bfi_1", "bfi_2", "bfi_3", "bfi_4", "bfi_5", "macqj_1", "macqj_2", "macqj_3", "macqj_4", "macqj_5", "macqj_6", "macqj_7", "macqj_8", "macqj_9", "macqj_10", "macqj_11", "macqj_12", "macqj_13", "macqj_14", "macqj_15", "macqj_16", "macqj_17", "macqj_18", "macqj_19", "macqj_20", "macqj_21", "macqr_1", "macqr_2", "macqr_3", "macqr_4", "macqr_5", "macqr_6", "macqr_7", "macqr_8", "macqr_9", "macqr_10", "macqr_11", "macqr_12", "macqr_13", "macqr_14", "macqr_15", "macqr_16", "macqr_17", "macqr_18", "macqr_19", "macqr_20", "macqr_21", "sex")) #> A tidy_sem object #> v $dictionary #> o $data #> o $syntax suppressMessages(tidy_sem(c("bfi_1", "bfi_2", "bfi_3", "bfi_4", "bfi_5", "mac_q_j_1", "mac_q_j_2", "mac_q_j_3", "mac_q_j_4", "mac_q_j_5", "mac_q_j_6", "mac_q_j_7", "mac_q_j_8", "mac_q_j_9", "mac_q_j_10", "mac_q_j_11", "mac_q_j_12", "mac_q_j_13", "mac_q_j_14", "mac_q_j_15", "mac_q_j_16", "mac_q_j_17", "mac_q_j_18", "mac_q_j_19", "mac_q_j_20", "mac_q_j_21", "mac_q_r_1", "mac_q_r_2", "mac_q_r_3", "mac_q_r_4", "mac_q_r_5", "mac_q_r_6", "mac_q_r_7", "mac_q_r_8", "mac_q_r_9", "mac_q_r_10", "mac_q_r_11", "mac_q_r_12", "mac_q_r_13", "mac_q_r_14", "mac_q_r_15", "mac_q_r_16", "mac_q_r_17", "mac_q_r_18", "mac_q_r_19", "mac_q_r_20", "mac_q_r_21"))) #> A tidy_sem object #> v $dictionary #> o $data #> o $syntax ``` -------------------------------- ### Example of generating measurement syntax Source: https://cjvanlissa.github.io/tidySEM/reference/measurement.html Demonstrates creating a dictionary from variable names and generating the corresponding measurement model syntax. ```R dict <- tidy_sem(c("bfi_1", "bfi_2", "bfi_3", "bfi_4", "bfi_5")) measurement(dict) #> A tidy_sem object #> v $dictionary #> o $data #> v $syntax ``` -------------------------------- ### Example: Estimate a 2-class growth mixture model Source: https://cjvanlissa.github.io/tidySEM/reference/mx_growth_mixture.html This example demonstrates how to use `mx_growth_mixture` to estimate a 2-class growth mixture model. It defines a growth model for 'empathy' data and specifies two latent classes. Ensure the 'empathy' dataset is loaded before running. ```R if (FALSE) { # \dontrun{ data("empathy") df <- empathy[1:6] mx_growth_mixture(model = "i =~ 1*ec1 + 1*ec2 + 1*ec3 +1*ec4 +1*ec5 +1*ec6 s =~ 0*ec1 + 1*ec2 + 2*ec3 +3*ec4 +4*ec5 +5*ec6 ec1 ~~ vec1*ec1 ec2 ~~ vec2*ec2 ec3 ~~ vec3*ec3 ec4 ~~ vec4*ec4 ec5 ~~ vec5*ec5 ec6 ~~ vec6*ec6 i ~~ 0*i s ~~ 0*s i ~~ 0*s", classes = 2, data = df) -> res } # } ``` -------------------------------- ### mixture_starts Function Source: https://cjvanlissa.github.io/tidySEM/reference/mixture_starts.html Automatically sets starting values for an OpenMx mixture model created with tidySEM. ```APIDOC ## mixture_starts(model, splits, ...) ### Description Automatically set starting values for an OpenMx mixture model. This function is designed for mixture models created using tidySEM functions like mx_mixture. ### Arguments - **model** (mxModel) - Required - A mixture model of class mxModel. - **splits** (numeric vector) - Optional - A numeric vector of length equal to the number of rows in the mxData used in the model object. If not provided, defaults to k-means clustering. - **...** (dots) - Optional - Additional arguments passed to functions. ### Value Returns an OpenMx::mxModel() with starting values. ### Request Example ```r # Example usage df <- iris[, 1, drop = FALSE] names(df) <- "x" mod <- mx_mixture(model = "x ~ m{C}*1 x ~~ v{C}*x", classes = 2, data = df, run = FALSE) mod <- mixture_starts(mod) ``` ``` -------------------------------- ### Example of dummy coding with iris dataset Source: https://cjvanlissa.github.io/tidySEM/reference/mx_dummies.html Demonstrates applying dummy coding to a subset of the iris dataset when OpenMx is available. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ mx_dummies(iris[1:5,]) } ``` -------------------------------- ### Example of editing graph nodes Source: https://cjvanlissa.github.io/tidySEM/reference/edit_graph.html Demonstrates preparing a graph and modifying node properties using edit_graph. ```R p <- prepare_graph(layout = get_layout("x", rows = 1)) p <- edit_graph(p, {colour = "blue"}, element = "nodes") plot(p) ``` -------------------------------- ### Example of adding paths to a model Source: https://cjvanlissa.github.io/tidySEM/reference/add_paths.html Demonstrates initializing a tidy_sem object, applying measurement specifications, adding paths, and estimating the model using lavaan. ```R library(lavaan) #> This is lavaan 0.6-21 #> lavaan is FREE software! Please report any bugs. df <- iris[, 1:4] names(df) <- paste0("x_", 1:4) model <- tidy_sem(df) model <- measurement(model) model <- add_paths(model, x =~ a*x_1 + b*x_2 + a*x_3 + b*x_4) res <- estimate_lavaan(model) #> Warning: lavaan->lav_object_post_check(): #> some estimated ov variances are negative summary(res) #> lavaan 0.6-21 ended normally after 31 iterations #> #> Estimator ML #> Optimization method NLMINB #> Number of model parameters 11 #> #> Number of observations 150 #> #> Model Test User Model: #> #> Test statistic 359.420 #> Degrees of freedom 3 #> P-value (Chi-square) 0.000 #> #> Parameter Estimates: #> #> Standard errors Standard #> Information Expected #> Information saturated (h1) model Structured #> #> Latent Variables: #> Estimate Std.Err z-value P(>|z|) #> x =~ #> x_1 (a) 1.000 #> x_2 (b) -0.139 0.029 -4.717 0.000 #> x_3 (a) 1.000 #> x_4 (b) 0.752 0.038 19.760 0.000 #> #> Intercepts: #> Estimate Std.Err z-value P(>|z|) #> .x_1 5.843 0.105 55.447 0.000 #> .x_2 3.057 0.035 86.196 0.000 #> .x_3 3.758 0.110 34.094 0.000 #> .x_4 1.199 0.062 19.335 0.000 #> x 0.000 #> #> Variances: #> Estimate Std.Err z-value P(>|z|) #> .x_1 0.535 0.070 7.689 0.000 #> .x_2 0.167 0.019 8.808 0.000 #> .x_3 0.691 0.085 8.092 0.000 #> .x_4 -0.063 0.021 -2.972 0.003 #> x 1.131 0.168 6.743 0.000 ``` -------------------------------- ### Example: Plotting a mixture model Source: https://cjvanlissa.github.io/tidySEM/reference/plot_bivariate.html Demonstrates creating a bivariate plot for a 2-class mixture model using the OpenMx backend. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ library(OpenMx) iris_sample <- iris[c(1:5, 145:150), c("Sepal.Length", "Sepal.Width")] names(iris_sample) <- c("x", "y") res <- mx_profiles(iris_sample, classes = 2) plot_bivariate(res, rawdata = FALSE) } ``` -------------------------------- ### Example: Extracting and viewing nodes Source: https://cjvanlissa.github.io/tidySEM/reference/nodes.html Demonstrates how to create a simple graph, prepare it, and then extract its node attributes using the `nodes()` function. The output shows the default node properties. ```R edg <- data.frame(from = "x", to = "y") p <- prepare_graph(edges = edg, layout = get_layout("x", "y", rows = 1)) nodes(p) ``` -------------------------------- ### Example of conf_int usage Source: https://cjvanlissa.github.io/tidySEM/reference/conf_int.html Demonstrates creating confidence intervals from a numeric vector and standard errors. ```R conf_int(x = c(1.325, 2.432), se = c(.05336, .00325)) #> [1] "[1.22, 1.43]" "[2.43, 2.44]" ``` -------------------------------- ### Example: Estimate a 2-class LCA model Source: https://cjvanlissa.github.io/tidySEM/reference/mx_lca.html This example demonstrates how to use mx_lca to fit a latent class analysis with 2 classes. Ensure your data is appropriately formatted, especially for ordinal indicators. ```R if (FALSE) { # \dontrun{ df <- data_mix_ordinal df[1:4] <- lapply(df, ordered) mx_lca(data = df, classes = 2) -> res } ``` -------------------------------- ### Example of extracting a dictionary Source: https://cjvanlissa.github.io/tidySEM/reference/dictionary.html Demonstrates extracting the dictionary from a tidy_sem object created from the iris dataset. ```R dict <- tidy_sem(iris, split = "\\.") dictionary(dict) #> name scale type label #> 1 Sepal.Length Sepal observed Sepal.Length #> 2 Sepal.Width Sepal observed Sepal.Width #> 3 Petal.Length Petal observed Petal.Length #> 4 Petal.Width Petal observed Petal.Width #> 5 Species observed Species ``` -------------------------------- ### Example usage of estimate_lavaan Source: https://cjvanlissa.github.io/tidySEM/reference/estimate_lavaan.html Demonstrates initializing a tidy_sem model, applying measurement specifications, and estimating the model using lavaan. ```R library(lavaan) model <- tidy_sem(iris, "\\.") model <- measurement(model) res <- estimate_lavaan(model) summary(res) ``` -------------------------------- ### Example usage of plot_profiles Source: https://cjvanlissa.github.io/tidySEM/reference/plot_profiles.html Demonstrates how to use the plot_profiles function with sample data. This example customizes the plot by removing error bars and standard deviation boxes, and disabling raw data plotting. ```R df_plot <- data.frame(Variable = "x1", Class = "class1", Classes = 1, Model = "equal var 1", Value = 3.48571428571429, se = 0.426092805342181, Value.Variances = 3.81265306156537, se.Variances = 1.17660769119959) plot_profiles(list(df_plot = df_plot, df_raw = NULL), ci = NULL, sd = FALSE, add_line = FALSE, rawdata = FALSE, bw = FALSE) ``` -------------------------------- ### Example of plotting growth trajectories Source: https://cjvanlissa.github.io/tidySEM/reference/plot_growth.html Demonstrates fitting a growth mixture model and visualizing the results using plot_growth. ```R if (FALSE) { # \dontrun{ data("empathy") df <- empathy[1:6] mx_growth_mixture(model = "i =~ 1*ec1 + 1*ec2 + 1*ec3 +1*ec4 +1*ec5 +1*ec6 s =~ 0*ec1 + 1*ec2 + 2*ec3 +3*ec4 +4*ec5 +5*ec6 ec1 ~~ vec1*ec1 ec2 ~~ vec2*ec2 ec3 ~~ vec3*ec3 ec4 ~~ vec4*ec4 ec5 ~~ vec5*ec5 ec6 ~~ vec6*ec6 i ~~ 0*i s ~~ 0*s i ~~ 0*s", classes = 2, data = df) -> res plot_growth(res, rawdata = FALSE) } # } ``` -------------------------------- ### Example of extracting syntax from a tidy_sem object Source: https://cjvanlissa.github.io/tidySEM/reference/syntax.html Demonstrates initializing a tidy_sem object, adding paths, and retrieving the resulting syntax data frame. ```R dict <- tidy_sem(iris, split = "\\.") dict <- add_paths(dict, Sepal.Width ~~ Sepal.Length) syntax(dict) #> lhs op rhs block group free label ustart plabel #> 1 Sepal.Width ~~ Sepal.Length 1 1 1 NA .p1. #> 2 Sepal.Width ~~ Sepal.Width 1 1 1 NA .p2. #> 3 Sepal.Length ~~ Sepal.Length 1 1 1 NA .p3. #> 4 Sepal.Width ~1 1 1 1 NA .p4. #> 5 Sepal.Length ~1 1 1 1 NA .p5. ``` -------------------------------- ### Define user-specific layouts Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Examples of defining custom layouts for specific model types like mediation or CFA. ```R get_layout("x", "y", rows = 1) #> [,1] [,2] #> [1,] "x" "y" #> attr(,"class") #> [1] "layout_matrix" "matrix" "array" ``` ```R get_layout("", "m", "", "x", "", "y", rows = 2) #> [,1] [,2] [,3] #> [1,] "" "m" "" #> [2,] "x" "" "y" #> attr(,"class") #> [1] "layout_matrix" "matrix" "array" ``` ```R get_layout("", "F", "", "y1", "y2", "y3", rows = 2) #> [,1] [,2] [,3] #> [1,] "" "F" "" #> [2,] "y1" "y2" "y3" #> attr(,"class") #> [1] "layout_matrix" "matrix" "array" ``` -------------------------------- ### Load Required R Packages Source: https://cjvanlissa.github.io/tidySEM/articles/lca_lcga.html Loads the tidySEM, ggplot2, and MASS packages. Ensure these are installed before running. ```r library(tidySEM) library(ggplot2) library(MASS) ``` -------------------------------- ### Example of paste2 usage Source: https://cjvanlissa.github.io/tidySEM/reference/paste2.html Demonstrates how paste2 removes NA values during string concatenation. ```R paste2("word", NA) #> [1] "word" ``` -------------------------------- ### Example of class_prob usage Source: https://cjvanlissa.github.io/tidySEM/reference/class_prob.html Demonstrates how to run a mixture model and extract class probabilities using the class_prob function. ```R if (FALSE) { # \dontrun{ df <- iris[, 1, drop = FALSE] names(df) <- "x" res <- mx_mixture(model = "x ~ m{C}*1 x ~~ v{C}*x", classes = 1, data = df) class_prob(res) } # } ``` -------------------------------- ### Usage of pseudo_class function Source: https://cjvanlissa.github.io/tidySEM/reference/pseudo_class.html Demonstrates the basic usage of the pseudo_class function with different model specifications (expression, lm function, character string, and function). Ensure OpenMx is installed and loaded. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ library(OpenMx) set.seed(2) dat <- iris[c(1:5, 50:55, 100:105), 1:4] colnames(dat) <- c("SL", "SW", "PL", "PW") fit <- suppressWarnings(mx_profiles(data = dat, classes = 3)) pct_mx <- pseudo_class(x = fit, model = "SL ~ class", data = dat, m = 2) pct_lm <- pseudo_class(x = fit, model = lm( SL ~ class, data = data), data = dat, m = 2) pcte <- pseudo_class(x = fit, model = lm(SL ~ class, data = data), data = dat, m = 2) pct_func <- pseudo_class(x = fit, model = function(data){lm(SL ~ class, data = data)}, data = dat, m = 2) } ``` -------------------------------- ### Estimate Model with OpenMx Syntax Source: https://cjvanlissa.github.io/tidySEM/articles/Generating_syntax.html Estimate the model using OpenMx syntax via the `estimate_mx` function. Ensure the OpenMx R-package is installed. ```R model %>% estimate_mx() ``` -------------------------------- ### Simulate Mixed-Type Example Data Source: https://cjvanlissa.github.io/tidySEM/articles/mixed_lca.html Generates a dataset with three continuous indicators and one ordinal indicator for latent class modeling. ```R set.seed(10) n <- 200 # Set class-specific means class_means <- c(rep(0, floor(0.3 * n)), rep(2, ceiling(0.7 * n))) # Simulate continuous indicators df <- rnorm(4 * n, mean = rep(class_means, 4)) df <- matrix(df, nrow = n) df <- t(t(df) * c(1, 2, 0.5, 1)) df <- data.frame(df) names(df) <- paste0("X", 1:4) # Convert one indicator to ordinal df$X4 <- cut(df$X4, breaks = 3, labels = FALSE) df$X4 <- mxFactor(df$X4, levels = 1:3) ``` -------------------------------- ### Dynamic model generation with {C} placeholder Source: https://cjvanlissa.github.io/tidySEM/reference/mx_mixture.html Example demonstrating dynamic model generation using the `{C}` placeholder in lavaan syntax for class-specific parameter labels and equality constraints. Requires a data frame with at least one column named 'x'. ```R df <- iris[, 1, drop = FALSE] names(df) <- "x" mx_mixture(model = "x ~ m{C}*1 x ~~ v{C}*x", classes = 1, data = df) ``` -------------------------------- ### Estimate a latent profile model Source: https://cjvanlissa.github.io/tidySEM/reference/mx_profiles.html Example of running a latent profile analysis with two classes using the empathy dataset. ```R if (FALSE) { # \dontrun{ data("empathy") df <- empathy[1:6] mx_profiles(data = df, classes = 2) -> res } # } ``` -------------------------------- ### Estimate mixed data latent class analysis Source: https://cjvanlissa.github.io/tidySEM/reference/mx_mixed_lca.html Example demonstrating data preparation with ordinal indicators and model estimation using mx_mixed_lca. ```R if (FALSE) { # \dontrun{ if(isTRUE(requireNamespace("OpenMx", quietly = TRUE))) { library(tidySEM) library(OpenMx) # Construct dataset with ordinal and categorical indicators set.seed(1) n = 200 mns <- c(rep(0, floor(.3*n)), rep(2, ceiling(.7*n))) df <- rnorm(4*n, mean = rep(mns, 4)) df <- matrix(df, nrow = n) df <- t(t(df) * c(1, 2, .5, 1)) df <- data.frame(df) df$X4 <- cut(df$X4, 3, labels = FALSE) df$X4 <- OpenMx::mxFactor(df$X4, levels = c(1:3)) # Estimate the model set.seed(1) res <- mx_mixed_lca(data = df, classes = 2) } } # } ``` -------------------------------- ### Create scale scores from a tidy_sem object Source: https://cjvanlissa.github.io/tidySEM/reference/create_scales.html This example shows how to create scale scores directly from a 'tidy_sem' object, which is generated by the tidy_sem function. It highlights potential issues like negative factor loadings and provides a summary of the resulting scale descriptives. ```R dict <- tidy_sem(iris, split = "\".") create_scales(dict) #> Some factor loadings were negative for scale 'Sepal'. These items were automatically reversed: Sepal.Length #> Number of categories should be increased in order to count frequencies. #> A tidy_scales object #> v $descriptives #> v $correlations #> v $scores #> #> Subscale Items n mean sd min max skew skew_2se kurt kurt_2se #> 1 Sepal 2.00 150.00 2.61 0.49 1.45 3.50 0.09 0.24 1.99 2.53 #> 2 Petal 2.00 150.00 2.48 1.25 0.60 4.60 -0.26 -0.66 1.57 1.99 #> Reliability Interpret min_load max_load #> 1 -0.27(sb) Unacceptable 0.34 0.34 #> 2 0.98(sb) Good 0.98 0.98 ``` -------------------------------- ### Calculate scale scores using iris dataset Source: https://cjvanlissa.github.io/tidySEM/reference/create_scales.html This example demonstrates how to use the create_scales function with the iris dataset to calculate scale scores. It shows the resulting descriptive statistics for the created scale. ```R out <- create_scales(iris, keys.list = list(scalename = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"))) #> Warning: When computing factor loadings for scalename: An ultra-Heywood case was detected. Examine the results carefully #> Number of categories should be increased in order to count frequencies. out$descriptives #> Subscale Items n mean sd min max skew skew_2se kurt kurt_2se #> 1 scalename 4.00 150.00 3.46 0.78 2.10 5.10 -0.01 -0.02 1.82 2.32 #> Reliability Interpret min_load max_load #> 1 0.71 Acceptable NA NA ``` -------------------------------- ### Load Data and Packages Source: https://cjvanlissa.github.io/tidySEM/articles/lca_confirmatory.html Initializes the environment and selects specific indicator variables for the analysis. ```R # Load required packages library(tidySEM) library(ggplot2) library(OpenMx) # Load data df <- zegwaard_carecompass[, c("burdened", "trapped", "negaffect", "loneliness")] ``` -------------------------------- ### Load required packages Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Initializes the environment with tidySEM, lavaan, ggplot2, and dplyr. ```R library(tidySEM) library(lavaan) library(ggplot2) library(dplyr) ``` -------------------------------- ### GET /get_fit Source: https://cjvanlissa.github.io/tidySEM/reference/get_fit.html Retrieves fit indices from a model object. ```APIDOC ## GET get_fit ### Description Get fit indices from objects for which a method exists. ### Method GET ### Endpoint get_fit(x, ...) ### Parameters #### Arguments - **x** (object) - Required - An object for which a method exists. - **...** (dots) - Optional - Further arguments to be passed to or from other methods. ### Response - **Value** (data.frame) - A data.frame containing the fit indices. ### Request Example get_fit(model_object) ### Response Example { "AIC": 123.45, "BIC": 130.22, "RMSEA": 0.05 } ``` -------------------------------- ### Estimate a structural equation model with OpenMx Source: https://cjvanlissa.github.io/tidySEM/reference/estimate_mx.html Demonstrates the workflow of preparing a tidy_sem model and estimating it using the OpenMx engine. ```R df <- iris[1:4] names(df) <- paste0("x_", 1:4) model <- tidy_sem(df) model <- measurement(model) res <- estimate_mx(model) summary(res) ``` -------------------------------- ### Accessing and Modifying the Dictionary Source: https://cjvanlissa.github.io/tidySEM/reference/dictionary.html Provides functions to get or set the dictionary attribute of a tidy_sem object. ```APIDOC ## Accessing and Modifying the Dictionary ### Description Provides functions to get or set the dictionary attribute of a `tidy_sem` object. ### Usage ```R dictionary(x) dictionary(x) <- value ``` ### Arguments * `x` (tidy_sem): Object of class tidy_sem. * `value` (any): A valid value for `dictionary(x)`. ### Value A data.frame representing the dictionary. ### Examples ```R dict <- tidy_sem(iris, split = ".") dictionary(dict) ``` ``` -------------------------------- ### Estimate and summarize OpenMx models Source: https://cjvanlissa.github.io/tidySEM/articles/Tabulating_results.html Requires the OpenMx package to be loaded. Use estimate_mx to run the model, followed by table_results and table_fit to generate output tables. ```R library(OpenMx) model |> estimate_mx() -> fit_mx table_results(fit_mx) table_fit(fit_mx) ``` -------------------------------- ### GET /data/maene_identity Source: https://cjvanlissa.github.io/tidySEM/reference/maene_identity.html Access the maene_identity dataset documentation for use in structural equation modeling and latent class analysis. ```APIDOC ## GET /data/maene_identity ### Description Retrieves the synthetic dataset 'maene_identity' containing 439 rows and 13 variables related to adolescent identity, discrimination, and depression. ### Method GET ### Endpoint data(maene_identity) ### Parameters #### Request Body - **N/A** ### Response #### Success Response (200) - **Ethnic_1** (ordered) - Belonging to group (5-point Likert) - **Ethnic_2** (ordered) - Strong sense of belonging (5-point Likert) - **Ethnic_3** (ordered) - Member of group (5-point Likert) - **Belgian** (ordered) - Member of Belgian group (10-point Likert) - **Flemish** (ordered) - Member of Flemish group (10-point Likert) - **age** (numeric) - Participant age - **sex** (factor) - Participant sex - **ses** (numeric) - Socio-economic status (ISEI) - **belgianborn** (factor) - Born in Belgium status - **age_belgium** (numeric) - Age at migration to Belgium - **vict_bully** (factor) - Victim of peer bullying - **vict_teacher** (factor) - Victim of teacher discrimination - **depression** (numeric) - Depressive feelings scale score ### Response Example { "dataset": "maene_identity", "rows": 439, "columns": 13 } ``` -------------------------------- ### Load Required Packages Source: https://cjvanlissa.github.io/tidySEM/articles/mixed_lca.html Ensure tidySEM and OpenMx are loaded before using mixed-data LCA functions. ```R library(tidySEM) library(OpenMx) ``` -------------------------------- ### Load alkema_microplastics Dataset Source: https://cjvanlissa.github.io/tidySEM/reference/alkema_microplastics.html This code snippet loads the alkema_microplastics dataset. Ensure the tidySEM package is installed and loaded before use. ```R data(alkema_microplastics) ``` -------------------------------- ### Create a basic graph with a single node Source: https://cjvanlissa.github.io/tidySEM/articles/sem_graph.html Use `graph_sem` with a layout matrix to define the structure. `coord_fixed()` ensures aspect ratio. ```R graph_sem(layout = matrix("x")) + coord_fixed() ``` -------------------------------- ### Perform BCH Model Analysis Source: https://cjvanlissa.github.io/tidySEM/articles/lca_ordinal.html Prepares the data and fits a BCH model to analyze the relationship between variables. ```R df_aux$vict_teacher <- (as.integer(df_aux$vict_teacher) - 1) aux_model <- BCH(res_final, model = "depression ~ vict_teacher", data = df_aux) ``` -------------------------------- ### Estimate Model with Mplus Syntax Source: https://cjvanlissa.github.io/tidySEM/articles/Generating_syntax.html Estimate the model using Mplus syntax through the `estimate_mplus` function. This requires MplusAutomation R-package and Mplus to be installed. ```R library(MplusAutomation) model %>% estimate_mplus() ``` -------------------------------- ### Load Layout from Clipboard Source: https://cjvanlissa.github.io/tidySEM/reference/get_layout.html Load a layout matrix directly from the system clipboard. This method requires different commands for Windows and Mac operating systems. ```R # On Windows, run: read.table("clipboard", sep = "\t") # On Mac, run: read.table(pipe("pbpaste"), sep="\t") ``` -------------------------------- ### Add multiple paths with quoted and unquoted arguments Source: https://cjvanlissa.github.io/tidySEM/articles/Generating_syntax.html Shows how to add both a regression path and a cross-loading simultaneously using a mix of quoted and unquoted syntax. ```R model |> add_paths("vis ~ tex", vis =~ spe_1) |> estimate_lavaan() ``` -------------------------------- ### Get Model Parameter Names in R Source: https://cjvanlissa.github.io/tidySEM/articles/lca_lcga.html Retrieves the names of all parameters estimated in a statistical model. This is useful for specifying hypotheses in subsequent analyses. ```r names(coef(res_final)) ``` -------------------------------- ### Load tidySEM and Data Source: https://cjvanlissa.github.io/tidySEM/articles/lca_ordinal.html Attach the tidySEM package and assign the maene_identity dataset to a local object. ```R # Load required packages library(tidySEM) library(ggplot2) # Load data df <- maene_identity[1:5] ``` -------------------------------- ### Compare Alternative Model Specifications Source: https://cjvanlissa.github.io/tidySEM/articles/lca_confirmatory.html Compares a theoretical model against an alternative specification, such as estimating variances freely across classes. This involves creating a list of models and then generating a fit table for comparison. The 'df' is your data, 'res[[4]]' is the theoretical model, and 'res_alt' is the alternative. ```R res_alt <- mx_profiles(df, classes = 4, variances = "varying") compare <- list(res[[4]], res_alt) table_fit(compare) ``` -------------------------------- ### Coloring Positive Edges Green Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Conditionally colors edges green if their estimated value is positive. This is a basic example of using the `color_pos_edges` function for visual customization. ```R set.seed(6) prepare_graph(fit) %>% color_pos_edges("green") %>% plot() ``` -------------------------------- ### Get Model Nodes in TidySEM Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Use `get_nodes()` to retrieve a list of all nodes (latent and observed variables) in your fitted TidySEM model. This helps in verifying the model structure. ```R get_nodes(fit) #> name shape label #> 1 visual oval visual #> 2 textual oval textual #> 3 speed oval speed #> 4 x1 rect x1 #> 5 x2 rect x2 #> 6 x3 rect x3 #> 7 x4 rect x4 #> 8 x5 rect x5 #> 9 x6 rect x6 #> 10 x7 rect x7 #> 11 x8 rect x8 #> 12 x9 rect x9 ``` -------------------------------- ### Import layout from external sources Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Reads layout matrices from CSV files or system clipboards. ```R read.csv("example.csv") ``` ```R read.table("clipboard", sep = "\t") ``` ```R read.table(pipe("pbpaste"), sep="\t") ``` -------------------------------- ### Convert lavaan syntax to RAM specification Source: https://cjvanlissa.github.io/tidySEM/reference/as_ram.html The `as_ram` function converts SEM models specified in lavaan syntax into the RAM (Reticular Action Model) specification required by the OpenMx package. ```APIDOC ## POST /api/convert/lavaan-to-ram ### Description Converts a structural equation model specified using lavaan syntax into the RAM specification for OpenMx. ### Method POST ### Endpoint /api/convert/lavaan-to-ram ### Parameters #### Request Body - **x** (string | object) - Required - The user-specified model using lavaan model syntax, or a tidy_sem object. - **groups** (string) - Optional - Character, either corresponding to the name of a column in `data`, or else a vector of group names. - **data** (object) - Optional - A data frame which is added to the model. - **threshold_method** (string) - Optional - Method used to specify thresholds for ordinal indicators. One of `c("mxThreshold", "mx_deviances")`. ### Request Example ```json { "x": "y ~ x", "groups": null, "data": null, "threshold_method": "mxThreshold" } ``` ### Response #### Success Response (200) - **model** (object) - An `mxModel` object representing the SEM in RAM specification. #### Response Example ```json { "model": { "type": "RAM", "matrices": { "A": { "name": "A", "free": true, "labels": null, "dimnames": [null, null], "byrow": false, "nrow": 2, "ncol": 2, "data": [[0, 0], [0, 0]] }, "S": { "name": "S", "free": true, "labels": null, "dimnames": [null, null], "byrow": false, "nrow": 2, "ncol": 2, "data": [[0, 0], [0, 0]] }, "F": { "name": "F", "free": true, "labels": null, "dimnames": [null, null], "byrow": false, "nrow": 2, "ncol": 2, "data": [[1, 0], [0, 1]] }, "M": { "name": "M", "free": true, "labels": null, "dimnames": [null, null], "byrow": false, "nrow": 2, "ncol": 1, "data": [[0], [0]] } }, "latentVars": [], "manifestVars": ["y", "x"], "data": null, "expectation": { "class": "MxExpectationRAM" }, "fitFunction": { "class": "MxFitFunctionML" } } } ``` ``` -------------------------------- ### Access and assign edges in sem_graph Source: https://cjvanlissa.github.io/tidySEM/reference/edges.html Use the `edges()` function to get or set the edges of a sem_graph object. Ensure the value assigned is a valid data frame for edges. ```R edges(x) edges(x) <- value ``` ```R edg <- data.frame(from = "x", to = "y") p <- prepare_graph(edges = edg, layout = get_layout("x", "y", rows = 1)) edges(p) ``` -------------------------------- ### Append Class Draws with OpenMx Source: https://cjvanlissa.github.io/tidySEM/reference/append_class_draws.html This snippet demonstrates how to append class draws to an OpenMx fit object using the append_class_draws function. It requires the OpenMx package to be installed and loaded. ```R if(requireNamespace("OpenMx", quietly = TRUE)){ library(OpenMx) dat <- iris[c(1:5, 50:55, 100:105),1:3] colnames(dat) <- letters[1:3] fit <- mx_profiles(data = dat, classes = 2) append_class_draws(fit, data = iris[c(1:5, 50:55, 100:105), 4, drop = FALSE]) } ``` -------------------------------- ### Estimate tidy_sem using 'OpenMx' Source: https://cjvanlissa.github.io/tidySEM/reference/estimate_mx.html The `estimate_mx` function is a wrapper for `as_ram` and `run_mx`, used to estimate a tidySEM model with OpenMx. ```APIDOC ## Estimate tidy_sem using 'OpenMx' ### Description This function is a wrapper for the `as_ram` and `run_mx` functions. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Arguments x An object of class `tidy_sem`. ... Additional parameters passed to the estimating function. ### Value An object of class `MxModel`. ### Examples ```R df <- iris[1:4] names(df) <- paste0("x_", 1:4) model <- tidy_sem(df) model <- measurement(model) res <- estimate_mx(model) summary(res) ``` ``` -------------------------------- ### Estimate tidy_sem using Mplus Source: https://cjvanlissa.github.io/tidySEM/reference/estimate_mplus.html The `estimate_mplus` function is a wrapper for `mplusObject` and `mplusModeler`. It requires Mplus to be installed and takes a `tidy_sem` object as input. Additional parameters can be passed to `mplusObject` and `mplusModeler`. ```APIDOC ## POST /estimate_mplus ### Description Estimates a structural equation model using Mplus by wrapping the `mplusObject` and `mplusModeler` functions. Requires Mplus to be installed. ### Method POST ### Endpoint /estimate_mplus ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (tidy_sem) - Required - An object of class `tidy_sem`. - **...** (any) - Optional - Additional parameters passed to `mplusObject` and `mplusModeler`. Arguments `rdata` and `MODEL` cannot be edited. ### Request Example ```json { "x": "", "run": 0 } ``` ### Response #### Success Response (200) - **mplusObject** (mplusObject) - An object of class `mplusObject`. #### Response Example ```json { "example": "" } ``` ### Details The arguments `dataout`, `modelout`, and `run` are optional. If not specified, the model will be run in `tempdir`. ``` -------------------------------- ### Load tidySEM and related libraries Source: https://cjvanlissa.github.io/tidySEM/articles/Tabulating_results.html Load the tidySEM package along with lavaan and MplusAutomation for structural equation modeling. ```r library(tidySEM) library(lavaan) library(MplusAutomation) ``` -------------------------------- ### Run OpenMx Model with Defaults Source: https://cjvanlissa.github.io/tidySEM/reference/run_mx.html Use run_mx to execute an OpenMx model with sensible defaults. This function is designed for use with tidySEM objects, converting them to mxModel and attempting to ensure convergence. ```R df <- iris[1:3] names(df) <- paste0("X_", 1:3) run_mx(measurement(tidy_sem(df), meanstructure = TRUE)) ``` -------------------------------- ### Custom Conditional Formatting with if_edit Source: https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html Illustrates using the generic `if_edit` function for custom conditional formatting. This example colors graph elements blue if their 'est' column contains the digit '4'. ```R prepare_graph(fit) %>% # Add color column to the graph elements edit_graph({ color = "black" }) %>% # Conditionally change color to blue when the column 'est' contains the number 4 if_edit(grepl("4", est), {color = "blue"}) %>% plot() ```