### Install and Use blavaan Basic Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/README.md This snippet shows how to install the blavaan package from GitHub and provides a minimal example of fitting a model and summarizing the results. Ensure you have the 'remotes' package installed for the GitHub installation. ```r # Install from CRAN or development version remotes::install_github("ecmerkle/blavaan") # Basic usage library(blavaan) model <- 'f =~ x1 + x2 + x3' fit <- blavaan(model, data = mydata) summary(fit) ``` -------------------------------- ### Install blavaan development version from GitHub Source: https://github.com/ecmerkle/blavaan/blob/master/README.md Use this command to install the latest development version of blavaan from GitHub. Compilation is required, and users relying on CRAN binaries may encounter issues. Consider R-universe for binary installations. ```R remotes::install_github("ecmerkle/blavaan", INSTALL_opts = "--no-multiarch") ``` -------------------------------- ### Multiple Group Model Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Illustrates how to fit a model separately for different groups using the 'group' argument. This snippet shows the basic model syntax and how to apply it with blavaan. ```r model <- ' f =~ x1 + x2 + x3 y ~ f ' fit <- blavaan(model, data = mydata, group = "groupvar") summary(fit) ``` -------------------------------- ### Installing runjags Package for JAGS Target Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md If you intend to use the JAGS target in blavaan, the 'runjags' package must be installed. This command shows how to install it. ```R install.packages("runjags") ``` -------------------------------- ### Automatic Target Detection for Priors Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-priors.md Shows how dpriors can automatically detect the target engine (Stan or JAGS) if not explicitly specified, based on installed packages. This example explicitly sets the target to Stan. ```r # dpriors detects installed packages and target automatically # If both rstan and runjags are installed, uses target argument dp <- dpriors(lambda = "normal(0, 5)", target = "stan") # Use Stan syntax ``` -------------------------------- ### Growth Model Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md An example of an unconditional linear growth model with four time points. It defines intercept and slope factors with appropriate loadings for each time point. ```r model <- ' # Define growth factors i =~ 1*y1 + 1*y2 + 1*y3 + 1*y4 # Intercept (all loadings = 1) s =~ 0*y1 + 1*y2 + 2*y3 + 3*y4 # Slope (loadings = time codes) ' fit <- bgrowth(model, data = longdata) ``` -------------------------------- ### Fit blavaan model with JAGS Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-blavaan-main.md Fits a structural equation model using blavaan with the JAGS target. Requires the 'runjags' package to be installed. This example demonstrates fitting the same model as the Stan example but using JAGS. ```r fit_jags <- blavaan(model, data = PoliticalDemocracy, target = "jags", n.chains = 3, burnin = 4000, sample = 10000) ``` -------------------------------- ### Configuring Seeds for JAGS Chains Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md For JAGS targets, the number of seeds provided must match the number of chains. This example demonstrates the correct way to specify seeds for three chains. ```R # Correct: one seed per chain fit <- blavaan(model, data = mydata, target = "jags", n.chains = 3, seed = c(123, 456, 789)) ``` -------------------------------- ### Simple Factor Analysis Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Example of a simple factor analysis with two factors, each measured by three indicators. This snippet shows the model definition and how to fit it using bcfa. ```r model <- ' f1 =~ x1 + x2 + x3 f2 =~ y1 + y2 + y3 ' fit <- bcfa(model, data = mydata) ``` -------------------------------- ### Using JAGS Distributions with JAGS Target in dpriors() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When the target is 'jags', use JAGS-syntax distributions (e.g., 'dnorm') within dpriors(). This example correctly specifies a normal distribution for 'lambda' when targeting JAGS. ```R dpriors(lambda = "dnorm(0, 1e-2)", target = "jags") ``` -------------------------------- ### Posterior Predictive Check Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md An example of using sampleData within a custom posterior predictive check function (ppmc_custom). This snippet demonstrates how to generate replicate data, fit the model to each replicate, calculate a fit measure (SRMR), and compare it to the observed fit measure to obtain a PPP-value. ```r ppmc_custom <- function(fit) { rep_list <- sampleData(fit, nrep = 100) obs_srmr <- fitMeasures(fit, "srmr") rep_srmr <- sapply(rep_list, function(dat) { fit_rep <- lavaan(model, data = dat) fitMeasures(fit_rep, "srmr") }) mean(rep_srmr > obs_srmr) # PPP-value } ``` -------------------------------- ### PPMC Function Examples Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md Demonstrates various ways to use the ppmc() function for posterior predictive model checking, including standard usage, custom fit measures, and custom discrepancy functions. ```r # Fit model fit <- blavaan(model, data = mydata) # Standard PPMC with default fit measures ppmc_result <- ppmc(fit) # Custom fit measures ppmc_result <- ppmc(fit, fit.measures = c("srmr", "rmsea", "cfi")) # Custom discrepancy function max_resid <- function(fit) max(abs(residuals(fit))) ppmc_result <- ppmc(fit, discFUN = max_resid) # Summary and visualization summary(ppmc_result) plot(ppmc_result) hist(ppmc_result) ``` -------------------------------- ### SEM with Mediation Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Demonstrates a structural equation model with mediation. It includes measurement models for a predictor factor, a mediator, and an outcome, along with the structural paths and the definition of an indirect effect. ```r model <- ' # Measurement models f1 =~ x1 + x2 + x3 m =~ m1 + m2 # Structural model m ~ f1 # Direct effect of f1 on m y ~ m + f1 # Effect of m on y, controlling for f1 # Indirect effect indirect := a * b a := coef("m~f1")[1] # Loading from f1 to m b := coef("y~m")[1] # Loading from m to y ' fit <- bsem(model, data = mydata) summary(fit) ``` -------------------------------- ### Using Stan Distributions with Stan Target in dpriors() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When the target is 'stan', use Stan-syntax distributions (e.g., 'normal') within dpriors(). This example correctly specifies a normal distribution for 'lambda' when targeting Stan. ```R dpriors(lambda = "normal(0, 10)", target = "stan") ``` -------------------------------- ### Access blavaan model results Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-blavaan-main.md Provides examples of how to access and inspect the results of a fitted blavaan model. Includes functions for summary statistics, coefficients, convergence diagnostics (PSRF/Rhat), and effective sample size (neff). ```r # Access results summary(fit) coef(fit) blavInspect(fit, "psrf") # Check convergence (Rhat) blavInspect(fit, "neff") # Effective sample size ``` -------------------------------- ### Consistent Distribution Syntax in dpriors() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When mixing distributions for different parameters in dpriors(), ensure all distributions match the target. This example shows an incorrect mix of JAGS and Stan syntax. ```R dpriors(lambda = "dnorm(0, 1e-2)", beta = "normal(0, 10)") ``` -------------------------------- ### Correct dpriors() Usage with Named Arguments Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When using the dpriors() function, arguments must be named. This example shows the correct way to specify a prior distribution for a parameter named 'lambda'. ```R dpriors(lambda = "normal(0,10)") # Correct ``` -------------------------------- ### Fit blavaan model with Stan (default) Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-blavaan-main.md Fits a structural equation model using blavaan with the default Stan target. Ensure the 'blavaan' and 'lavaan' libraries are loaded. The 'PoliticalDemocracy' dataset is used as an example. ```r library(blavaan) library(lavaan) # Political Democracy example model <- ' ind60 =~ x1 + x2 + x3 dem60 =~ y1 + y2 + y3 + y4 dem65 =~ y5 + y6 + y7 + y8 dem60 ~ ind60 dem65 ~ ind60 + dem60 y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' # Fit with Stan (default) fit <- blavaan(model, data = PoliticalDemocracy, n.chains = 3, burnin = 500, sample = 1000) ``` -------------------------------- ### Valid wiggle.sd Value Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md The wiggle.sd parameter must be a positive value. This example shows the correct way to set wiggle.sd. ```R wiggle.sd = 0.1 # Must be > 0 ``` -------------------------------- ### Bayesian Conditional Growth Model with Predictor (bgrowth) Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-convenience-functions.md Use bgrowth to fit conditional Bayesian latent growth curve models, including predictors. This example shows a growth model where 'group' predicts the intercept and slope. ```r # Growth model with group as predictor of intercept and slope model <- ' i =~ 1*y1 + 1*y2 + 1*y3 + 1*y4 s =~ 0*y1 + 1*y2 + 2*y3 + 3*y4 i ~ group s ~ group ' fit <- bgrowth(model, data = longdata, group = "group") summary(fit) ``` -------------------------------- ### Fit and Summarize Model with blavaan Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/README.md This snippet demonstrates the basic workflow for fitting a structural equation model using blavaan, checking for convergence, and viewing the summary of the results. Ensure the 'blavaan' library is loaded and 'mydata' is available. ```r library(blavaan) # 1. Fit model (read: api-blavaan-main.md or api-convenience-functions.md) model <- 'f =~ x1 + x2 + x3' fit <- blavaan(model, data = mydata, n.chains = 3) # 2. Check convergence (read: api-comparison-inspection.md) rhat <- blavInspect(fit, "rhat") all(rhat < 1.05) # TRUE = converged # 3. View results (read: api-methods-utilities.md) summary(fit) ``` -------------------------------- ### Manual Parameter Labeling with @ Syntax Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Demonstrates how to specify custom parameter labels using the '@' syntax in blavaan model strings. This is useful for clarity and for applying constraints. ```r model <- ' f =~ x1 + x2 + x3 f @ L1 # Name this latent variable L1 y ~ f @ beta # Name this regression beta # Use in constraints y ~ c(beta, beta)*f # Same loading across groups ' ``` -------------------------------- ### summary() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Prints detailed parameter estimates with posterior summaries for a fitted blavaan model. It offers various options to include fit measures, standardized estimates, convergence diagnostics, and prior specifications. ```APIDOC ## summary() blavaan ### Description Print detailed parameter estimates with posterior summaries for a fitted blavaan model. ### Method S4 Method ### Signature ```r setMethod("summary", signature(object = "blavaan"), function(object, header = TRUE, fit.measures = FALSE, estimates = TRUE, ci = TRUE, standardized = FALSE, rsquare = FALSE, psrf = TRUE, neff = FALSE, postmedian = FALSE, postmode = FALSE, priors = TRUE, bf = FALSE, nd = 3L) ``` ### Parameters #### Path Parameters - **object** (blavaan) - Required - Fitted blavaan model. - **header** (logical) - Optional - Print brief model summary header. - **fit.measures** (logical) - Optional - Print Bayesian fit indices. - **estimates** (logical) - Optional - Print parameter estimates table. - **ci** (logical) - Optional - Include 95% credible intervals in estimates table. - **standardized** (logical) - Optional - Include standardized parameter estimates. - **rsquare** (logical) - Optional - Include R² values for observed variables. - **psrf** (logical) - Optional - Include potential scale reduction factors (convergence diagnostic). - **neff** (logical) - Optional - Include effective sample size. - **postmedian** (logical) - Optional - Include posterior median (default is mean). - **postmode** (logical) - Optional - Include posterior mode. - **priors** (logical) - Optional - Include prior specifications. - **bf** (logical) - Optional - Include standardized Bayes factors. - **nd** (integer) - Optional - Number of decimal places. ### Output Prints formatted table showing parameter labels, relationships, types, posterior estimates, standard errors/HPD bounds, posterior diagnostics, standardized estimates, and priors used. ### Request Example ```r fit <- blavaan(model, data = mydata) # Default summary summary(fit) # With convergence diagnostics and HPD intervals summary(fit, psrf = TRUE, neff = TRUE) # With standardized estimates and fit measures summary(fit, standardized = TRUE, fit.measures = TRUE) ``` ``` -------------------------------- ### Use 'cp' instead of deprecated 'ov.cp' and 'lv.cp' Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md The arguments ov.cp and lv.cp are deprecated. Use the 'cp' argument for control parameters. ```r Replace `ov.cp` and `lv.cp` with `cp`. ``` -------------------------------- ### show() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Prints an abbreviated summary of the blavaan object, typically called when the object is printed at the console. It includes a brief model description, marginal log-likelihood, and posterior predictive p-value. ```APIDOC ## show() blavaan ### Description Print abbreviated summary of the blavaan object. ### Method S4 Method ### Signature ```r setMethod("show", "blavaan", function(object) ``` ### Output - Brief model description - Marginal log-likelihood - Posterior predictive p-value ``` -------------------------------- ### Compare Two Models with blavaan Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/README.md This workflow illustrates how to fit two separate blavaan models and then compare them using the blavCompare function. This is useful for model selection in a Bayesian context. ```r # 1. Fit models (read: api-blavaan-main.md) fit1 <- blavaan(model1, data = mydata) fit2 <- blavaan(model2, data = mydata) # 2. Compare (read: api-comparison-inspection.md) blavCompare(fit1, fit2) ``` -------------------------------- ### Retrieving Fit Measures Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Shows how to get a named numeric vector of fit indices for a model fit object using the fitMeasures function. ```R fi <- fitMeasures(fit) names(fi) # Measure names: "chisq", "rmsea", "cfi", ... ``` -------------------------------- ### Plotting and Summarizing MCMC Draws Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Demonstrates basic plotting and summary statistics for MCMC draws. Requires the 'coda' package for summary. ```R param_draws <- as.matrix(draws[, "f1=~x1"]) # Plot diagnostics plot(draws) coda::summary(draws) ``` -------------------------------- ### Custom Discrepancy Function Example Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md Define and use a custom function to calculate the maximum absolute residual as a discrepancy measure for posterior predictive model checking. ```r # Custom function: maximum absolute residual max_abs_resid <- function(fit) { resid <- residuals(fit, type = "normalized") max(abs(resid)) } ppmc_result <- ppmc(object, discFUN = max_abs_resid) ``` -------------------------------- ### Fit a SEM model with blavaan Source: https://github.com/ecmerkle/blavaan/blob/master/README.md This snippet demonstrates how to define and fit a structural equation model using blavaan, similar to lavaan syntax. Ensure both lavaan and blavaan libraries are loaded. ```R library(lavaan) # for the PoliticalDemocracy data library(blavaan) 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 covariances y1 ~~ y5 y2 ~~ y4 + y6 y3 ~~ y7 y4 ~~ y8 y6 ~~ y8 ' fit <- bsem(model, data = PoliticalDemocracy) summary(fit) ``` -------------------------------- ### blavCompare() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Compares two fitted blavaan models using Bayes Factor Approximation, LOO, and WAIC. It helps in selecting the better model based on various information criteria. ```APIDOC ## blavCompare() ### Description Compares two fitted blavaan models using multiple information criteria including Bayes Factor Approximation, LOO, and WAIC. ### Signature ```r blavCompare(object1, object2, ...) ``` ### Parameters * `object1` (blavaan) - First fitted model object. * `object2` (blavaan) - Second fitted model object. * `...` - Additional arguments passed to `loo::loo_compare()`. ### Return Value An invisible list containing: * `bf` (numeric vector): Bayes factor approximation. * `loo` (list): Raw LOO objects for both models. * `diff_loo` (matrix): LOO comparison matrix. * `waic` (list): Raw WAIC objects for both models. * `diff_waic` (matrix): WAIC comparison matrix. ### Details Computes Bayes Factor Approximation (based on marginal log-likelihood), LOO (Pareto Smoothed Importance Sampling Leave-One-Out Cross-Validation), and WAIC (Watanabe-Akaike Information Criterion). ### Interpretation - **Bayes Factor**: exp(bf) > 1 favors object1; exp(bf) < 1 favors object2. Values >10 or <0.1 considered strong evidence. - **LOO/WAIC ELPD difference**: Negative values favor object1; positive values favor object2. Larger |difference| indicates stronger evidence. - **Standard Error**: Reported alongside difference; interpret relative to magnitude of difference. ### Requirements - Both models must have `test != "none"` (marginal likelihood computed). - Both models should use comparable data and targets for fair comparison. - For categorical models, comparison involves likelihood approximations (less precise). ### Example ```r # Fit two models model1 <- ' f =~ x1 + x2 + x3 ' model2 <- ' f =~ x1 + x2 + x3 + x4 + x5 ' fit1 <- blavaan(model1, data = mydata) fit2 <- blavaan(model2, data = mydata) # Compare models result <- blavCompare(fit1, fit2) # Prints LOO, WAIC, and Bayes factor approximations # Access components: result$bf # Bayes factors result$diff_loo # LOO comparison result$diff_waic # WAIC comparison ``` ``` -------------------------------- ### Automatic Parameters for bgrowth Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-convenience-functions.md These parameters are automatically set for the bgrowth convenience function. They can be overridden by passing arguments to `...`. ```r int.ov.free = FALSE, int.lv.free = TRUE, auto.fix.first = TRUE, auto.fix.single = TRUE, auto.var = TRUE, auto.cov.lv.x = TRUE, auto.cov.y = TRUE, auto.th = TRUE, auto.delta = TRUE ``` -------------------------------- ### blavInspect() - Initial Values and Parameters Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Extract initial MCMC values, covariance prior method, or default priors from a fitted blavaan object. ```APIDOC ## blavInspect() - Initial Values and Parameters ### Description Extracts initial MCMC values, the covariance prior method used, or default priors from a fitted blavaan object. ### Method `blavInspect(fit, what)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **fit**: A fitted blavaan object. * **what**: A character string specifying what to return. Accepts one of: `"start"`, `"starting.values"`, `"inits"`, `"cp"`, `"dp"`. ### Returns * `"start"`, `"starting.values"`, or `"inits"`: Named numeric vector of initial values used for MCMC chains. * `"cp"`: Character string indicating the covariance prior method used (`"srs"` or `"fa"`). * `"dp"`: Named character vector of default priors used. ### Example: ```r fit <- blavaan(model, data = mydata) initial_values <- blavInspect(fit, "inits") ``` -------------------------------- ### Refitting Model When do.fit is FALSE Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md If you encounter an error indicating that a component does not exist when `do.fit` is FALSE, refit the model with `do.fit = TRUE` or ensure `do.fit` is not set to FALSE. ```R fit <- blavaan(model, data = mydata, do.fit = TRUE) ``` -------------------------------- ### Refitting Models for Comparison Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When comparing models using `blavCompare`, ensure that neither model was fitted with `test='none'`. Refit the models with the default `test='standard'` or another valid test option. ```R # Refit models with test != "none" (default) fit1 <- blavaan(model1, data = mydata) # test="standard" by default fit2 <- blavaan(model2, data = mydata) blavCompare(fit1, fit2) ``` -------------------------------- ### Compute Fit Indices with Rescaling Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md Computes fit indices for a blavaan model, demonstrating the use of the 'devM' rescaling method and the 'loo' penalty. It also shows how to view the summary of the fit indices and compute incremental indices with a baseline model. ```r fit <- blavaan(model, data = mydata) # Compute fit indices with LOO penalty, deviance M rescaling fi <- blavFitIndices(fit, pD = "loo", rescale = "devM") # View summary with posterior means, SDs, HPD intervals summary(fi) # With baseline model (for incremental indices) fit_null <- blavaan(null_model, data = mydata) fi <- blavFitIndices(fit, baseline.model = fit_null) summary(fi) ``` -------------------------------- ### Implement Try-Catch for Blavaan Model Fitting Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md Use tryCatch to gracefully handle errors and warnings during Blavaan model fitting. This allows for custom error messages and prevents script termination. ```r fit_result <- tryCatch({ blavaan(model, data = mydata) }, error = function(e) { # Handle error cat("Model fitting failed:", e$message, "\n") NULL }, warning = function(w) { # Handle warning cat("Warning:", w$message, "\n") }) if (!is.null(fit_result)) { summary(fit_result) } ``` -------------------------------- ### Extract Posterior Samples with blavaan Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/README.md This workflow demonstrates how to extract various types of posterior samples after fitting a blavaan model, including MCMC draws, latent variable samples, and highest posterior density intervals. These samples can then be used for further analysis. ```r # 1. Fit model (read: api-blavaan-main.md) fit <- blavaan(model, data = mydata, save.lvs = TRUE) # 2. Extract samples (read: api-comparison-inspection.md) draws <- blavInspect(fit, "mcmc") # MCMC samples lvs <- blavInspect(fit, "lvs") # Latent variable samples hpd <- blavInspect(fit, "hpd", prob = 0.95) # 95% HPD intervals # 3. Use for analysis coda::summary(draws) apply(as.matrix(draws), 2, mean) # Posterior means ``` -------------------------------- ### Accessing MCMC Draws Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Shows how to retrieve MCMC draws using blavInspect and convert the resulting 'mcmc.list' object into a single matrix for combined analysis. ```r draws <- blavInspect(fit, "mcmc") # Returns mcmc.list # Convert to matrix (all chains combined) draws_matrix <- do.call("rbind", draws) dim(draws_matrix) # n_samples x n_parameters ``` -------------------------------- ### Parameter Multipliers for Fixed Values and Group Constraints Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Illustrates using parameter multipliers with '*' for fixing specific parameter values (e.g., loadings, intercepts) and 'c()' for constraining parameters across groups. ```r model <- ' f =~ x1 + 1*x2 + 0.5*x3 # Fixed loadings y ~ 0*f # No effect f ~ 0*1 # Mean = 0 # Across groups f =~ x1 + c(L1, L1)*x2 # x2 loading equal across groups y ~ c(B1, B2)*f # Different slopes by group ' ``` -------------------------------- ### Automatic Parameter Labeling Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Shows how blavaan automatically generates parameter labels from model syntax for factor loadings, regressions, and residual covariances. No explicit labeling is needed for these basic parameters. ```r model <- ' f =~ x1 + x2 + x3 # Generates: f=~x1, f=~x2, f=~x3 y ~ f # Generates: y~f x1 ~~ x2 # Generates: x1~~x2 x1 ~ 1 # Generates: x1~1 ' ``` -------------------------------- ### MCMC Control List Parameters Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Defines a list of MCMC control parameters for the lavaan initial fit, including maximum iterations and various tolerance levels. ```R list( iter.max = 100, # Iterations for lavaan initial fit steptol = 1e-5, # Step size tolerance ftol = 1e-6, # Function tolerance abstol = 1e-8, # Absolute tolerance reltol = 1e-10 # Relative tolerance ) ``` -------------------------------- ### plot() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Generates trace plots of MCMC chains for a fitted blavaan model, utilizing the bayesplot::mcmc_trace() function for visualization. This helps in assessing the mixing of MCMC chains. ```APIDOC ## plot() blavaan ### Description Generate trace plots of MCMC chains for a fitted blavaan model. ### Method S3 Method ### Signature ```r S3method(plot, blavaan) ``` ### Parameters #### Path Parameters - Standard plot parameters (main, xlab, ylab, etc.) ### Details Calls `bayesplot::mcmc_trace()` to visualize mixing of MCMC chains. Good chains show no trends or autocorrelation. ### Request Example ```r fit <- blavaan(model, data = mydata) plot(fit) # Trace plots for all parameters ``` ``` -------------------------------- ### Accessing Latent Variable Covariance Matrix Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Demonstrates how to obtain the latent variable covariance matrix using lavInspect. ```R cov_lv <- lavInspect(fit, "cov.lv") # Latent variable covariances ``` -------------------------------- ### Automatic Parameters for bcfa/bsem Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-convenience-functions.md These parameters are automatically set for bcfa and bsem convenience functions. They can be overridden by passing arguments to `...`. ```r int.ov.free = TRUE, int.lv.free = FALSE, auto.fix.first = TRUE, auto.fix.single = TRUE, auto.var = TRUE, auto.cov.lv.x = TRUE, auto.cov.y = TRUE, auto.th = TRUE, auto.delta = TRUE ``` -------------------------------- ### Constrained Model with Group Comparisons Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Demonstrates constraining parameters (e.g., loadings, means) to be equal across groups or fixing them to specific values. Uses `c(value1, value2)` for group-specific parameters and `*` for fixing values. ```r model <- ' f =~ x1 + c(L1, L1)*x2 + x3 f ~ c(M1, M2)*1 ' fit <- blavaan(model, data = mydata, group = "groupvar") # Loadings on x2 equal across groups # Factor means differ by group ``` -------------------------------- ### Compare Two Fitted blavaan Models Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Use blavCompare to compare two fitted blavaan models using Bayes Factor approximations, LOO, and WAIC. Ensure models have marginal likelihoods computed (test != 'none') and use comparable data. ```r model1 <- ' f =~ x1 + x2 + x3 ' model2 <- ' f =~ x1 + x2 + x3 + x4 + x5 ' fit1 <- blavaan(model1, data = mydata) fit2 <- blavaan(model2, data = mydata) # Compare models result <- blavCompare(fit1, fit2) # Prints LOO, WAIC, and Bayes factor approximations # Access components: result$bf # Bayes factors result$diff_loo # LOO comparison result$diff_waic # WAIC comparison ``` -------------------------------- ### Advanced Summary of blavaan Model Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Customizes the summary output to include convergence diagnostics (PSRF, neff) and HPD intervals. Use this when assessing model convergence and detailed interval information is required. ```R # With convergence diagnostics and HPD intervals summary(fit, psrf = TRUE, neff = TRUE) ``` -------------------------------- ### Generate Trace Plots for MCMC Chains Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Creates trace plots for all parameters in a fitted blavaan model using the bayesplot package. These plots visualize the mixing of MCMC chains, helping to diagnose convergence issues. ```R fit <- blavaan(model, data = mydata) plot(fit) # Trace plots for all parameters ``` -------------------------------- ### blavInspect() - Standard lavaan Extractions Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Access standard lavaan inspection outputs, including fit indices, estimates, and model-implied moments. ```APIDOC ## blavInspect() - Standard lavaan Extractions ### Description `blavInspect()` supports all standard `lavInspect()` extractions, providing access to various aspects of the fitted model, including fit indices, parameter estimates, covariance matrices, and implied moments. ### Method `blavInspect(fit, what, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **fit**: A fitted blavaan object. * **what**: A character string specifying the desired output. Supported values include: - `"fit.measures"`, `"fitMeasures"`: Fit indices (with Bayesian modifications). - `"est"`, `"estimates"`: Posterior point estimates (means by default). - `"vcov"`: Posterior covariance matrix of estimates. - `"se"`: Standard errors of estimates. - `"cor.lv"`, `"cov.lv"`: Latent variable covariance/correlation matrices. - `"cor.ov"`, `"cov.ov"`: Observed variable covariance/correlation matrices. - `"implied"`: Model-implied moments. - `"sample.cov"`, `"sample.mean"`: Observed data moments. - `"nobs"`, `"ntotal"`: Sample size. - `"ngroups"`, `"nlevels"`: Number of groups / levels (multilevel). - `"data"`: Raw data (subset). - `"options"`: All model fitting options. - `"partable"`: Full parameter table. * **...**: Additional arguments, such as `add.labels=TRUE/FALSE`, `prob=`, `level=`, passed to `lavaan` documentation. ### Returns Returns the requested information based on the `what` argument. ### Example: ```r fit <- blavaan(model, data = mydata) fit_indices <- blavInspect(fit, "fit.measures") parameter_table <- blavInspect(fit, "partable") ``` -------------------------------- ### Overriding Default auto.fix.first Constraint Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Demonstrates how to override the default behavior of fixing the first loading of each latent variable to 1. By setting the loading to NA, it becomes freely estimated. ```r # Override auto.fix.first model <- 'f =~ NA*x1 + x2 + x3' # x1 loading free; set scale elsewhere fit <- bcfa(model, data = mydata, std.lv = TRUE) # Latent SD = 1 ``` -------------------------------- ### Lavaan Model Syntax Operators Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Illustrates common operators used in Lavaan model syntax for defining latent variables, regressions, covariances, intercepts, thresholds, and defined parameters. ```R f =~ x1 + x2 + x3 # Latent variable definition y ~ f + x # Regression y ~~ e # Covariance y ~ 1 # Intercept/mean x1 | t1 + t2 # Ordinal thresholds a := b + c # Defined parameter ``` -------------------------------- ### Use Parameter Labels in Calculations Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Utilize parameter labels within defined parameters to dynamically extract and use parameter estimates in calculations. The `coef()` function can be used to retrieve these values. ```r model <- ' f =~ x1 + x2 + x3 # Extract parameter automatically with coef() indirect := a * b a := coef("f=~x1")[1] b := coef("y~f")[1] ' ``` -------------------------------- ### Default Summary of blavaan Model Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Prints a detailed summary of the fitted blavaan model, including parameter estimates and posterior summaries. Use the default summary for a quick overview of the model results. ```R fit <- blavaan(model, data = mydata) # Default summary summary(fit) ``` -------------------------------- ### blavInspect() - Chain and Sample Information Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Extract the number of MCMC chains from a fitted blavaan object. ```APIDOC ## blavInspect() - Chain and Sample Information ### Description Extracts the number of MCMC chains used in the analysis from a fitted blavaan object. ### Method `blavInspect(fit, what)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **fit**: A fitted blavaan object. * **what**: A character string specifying what to return. Accepts one of: `"n.chains"`, `"nchain"`, or `"nchains"`. ### Returns * `"n.chains"`, `"nchain"`, or `"nchains"`: Integer representing the number of MCMC chains. ### Example: ```r fit <- blavaan(model, data = mydata) num_chains <- blavInspect(fit, "nchains") ``` -------------------------------- ### Handle 'the following arguments are ignored' warning Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md This warning occurs when invalid lavaan arguments are passed to blavaan. Ensure only valid blavaan options are used. ```r blavaan WARNING: the following arguments are ignored ``` -------------------------------- ### Multiple Group Equality Constraints Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/model-specification.md Apply equality constraints across multiple groups for specific parameters. Use 'c(group1_value, group2_value)' to specify constraints. ```r model <- ' f =~ c(L1, L1)*x1 + c(L2, NA)*x2 + x3 # L1 equal, L2 only group 1 ' fit <- blavaan(model, data = mydata, group = "group") ``` -------------------------------- ### Handle 'fa priors are not available with stan' warning Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md When using Stan, 'fa' priors are unavailable and 'srs' priors will be used. This note informs about the fallback mechanism. ```r blavaan NOTE: fa priors are not available with stan. srs priors will be used. ``` -------------------------------- ### Check Model Convergence using blavInspect Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/errors.md Programmatically check if a Blavaan model has converged by examining Rhat values. If all Rhat values are below 1.05, the model is considered converged. ```r fit <- blavaan(model, data = mydata) # All Rhat values < 1.05 = converged rhat <- blavInspect(fit, "rhat") if (all(rhat < 1.05)) { # Model converged, safe to interpret summary(fit) } else { # Poor convergence warning("Model did not converge; consider rerunning with larger sample or adapt values") } ``` -------------------------------- ### Basic blavaan Model Specification Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-blavaan-main.md This snippet demonstrates the basic usage of blavaan() with a model defined using lavaan syntax. It specifies a measurement model with two latent factors and a regression between them, along with residual covariances. ```r model <- ' f1 =~ x1 + x2 + x3 f2 =~ y1 + y2 + y3 f2 ~ f1 x1 ~~ x2 ' fit <- blavaan(model, data = mydata) ``` -------------------------------- ### Generate Replicate Datasets Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md Generates a specified number of replicate datasets from a fitted blavaan model. The number of replicates is controlled by the `nrep` argument. The output is a list where each element is a replicate dataset. ```r fit <- blavaan(model, data = mydata) # Generate 100 replicate datasets rep_data <- sampleData(fit, nrep = 100) length(rep_data) # 100 head(rep_data[[1]]) # First replicate ``` -------------------------------- ### Accessing Parameter Table Data Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/classes-and-types.md Demonstrates how to access and filter the parameter table from a blavaan fit object. Use blavInspect to retrieve the table and standard R subsetting for filtering. ```r fit <- blavaan(model, data = mydata) partable <- blavInspect(fit, "partable") # Extract loadings only loadings <- partable[partable$op == "=~", ] # Get free parameters free_params <- partable[partable$free > 0, ] ``` -------------------------------- ### Inspect Convergence Diagnostics Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/configuration.md Extract and inspect convergence diagnostics such as Rhat and effective sample size (ESS) from a fitted blavaan object. Values < 1.05 for Rhat indicate convergence. Lower ESS values suggest less efficient sampling. ```r # Potential scale reduction factor (Rhat) # Values < 1.05 indicate convergence rhat <- blavInspect(fit, "rhat") all(rhat < 1.05) # TRUE = converged # Effective sample size (ESS) neff <- blavInspect(fit, "neff") min(neff) # Minimum ESS across parameters # ESS ratio neff_ratio <- neff / length(blavInspect(fit, "mcmc")) # Efficiency mean(neff_ratio) # Average efficiency (0-1) ``` -------------------------------- ### blavInspect() - Posterior Summaries Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-comparison-inspection.md Extract posterior mean, median, and mode estimates from a fitted blavaan object. ```APIDOC ## blavInspect() - Posterior Summaries ### Description Extracts posterior mean, median, or mode estimates from a fitted blavaan object. ### Method `blavInspect(fit, what)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **fit**: A fitted blavaan object. * **what**: A character string specifying what to return. Accepts one of: `"postmean"`, `"postmedian"`, `"postmode"`. ### Returns * `"postmean"`: Named numeric vector of posterior mean estimates. * `"postmedian"`: Named numeric vector of posterior median estimates. * `"postmode"`: Named numeric vector of posterior mode estimates (kernel density estimate). ### Example: ```r fit <- blavaan(model, data = mydata) post_means <- blavInspect(fit, "postmean") ``` -------------------------------- ### sampleData() / sampledata() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-diagnostics-prediction.md Generates replicate datasets from the posterior predictive distribution. An alias `sampledata()` is also available. ```APIDOC ## sampleData() / sampledata() ### Description Generate replicate datasets from the posterior predictive distribution. ### Signature ```r sampleData(object, nrep = NULL, conditional = FALSE, type = "response", simplify = FALSE, ...) sampledata(...) # Alias with lowercase 'd' ``` ``` -------------------------------- ### Custom Priors for Stan and JAGS Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-priors.md Allows for custom prior specifications for specific parameters like factor loadings and regression coefficients. Demonstrates setting priors for both Stan and JAGS targets. ```r # More informative priors on factor loadings dp <- dpriors(lambda = "normal(0, 5)", beta = "normal(0, 3)") fit <- blavaan(model, data = mydata, dp = dp) # Informative priors for JAGS dp <- dpriors(lambda = "dnorm(0, 1)", beta = "dnorm(0, 1)", target = "jags") fit <- blavaan(model, data = mydata, dp = dp, target = "jags") ``` -------------------------------- ### Set Default Target Option Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/configuration.md Sets the default MCMC engine for blavaan to Stan using R's options(). Subsequent blavaan() calls will use Stan by default. ```r options(blavaan.target = "stan") # Then blavaan() calls will default to Stan fit <- blavaan(model, data = mydata) # Uses Stan ``` -------------------------------- ### predict() Source: https://github.com/ecmerkle/blavaan/blob/master/_autodocs/api-methods-utilities.md Generates predictions from a fitted blavaan model, acting as a wrapper around the blavPredict() function. It can optionally use new data for predictions. ```APIDOC ## predict() blavaan ### Description Generate predictions from a fitted blavaan model (wrapper around `blavPredict()`). ### Method S4 Method ### Signature ```r setMethod("predict", "blavaan", function(object, newdata = NULL) ``` ### Parameters #### Path Parameters - **object** (blavaan) - Required - Fitted model. - **newdata** (data.frame) - Optional - New data (Stan only). ### Returns Same as `blavPredict(object, newdata=newdata, type="lv")`. ```