| Title: | Within-Subject Mediation Analysis Using Structural Equation Modeling |
|---|---|
| Description: | Within-subject mediation analysis using structural equation modeling. Examine how changes in an outcome variable between two conditions are mediated through one or more variables. Supports within-subject mediation analysis using the 'lavaan' package by Rosseel (2012) <doi:10.18637/jss.v048.i02>, and extends Monte Carlo confidence interval estimation to missing data scenarios using the 'semmcci' package by Pesigan and Cheung (2023) <doi:10.3758/s13428-023-02114-4>. |
| Authors: | Wendie Yang [aut, cre] (ORCID: <https://orcid.org/0009-0000-8388-6481>), Shu Fai Cheung [aut] (ORCID: <https://orcid.org/0000-0002-9871-9448>) |
| Maintainer: | Wendie Yang <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.2.0 |
| Built: | 2026-10-28 20:01:28 UTC |
| Source: | https://github.com/cran/wsMed |
Artificial data used to demonstrate model syntax, estimation, and categorical
predictors. The labels do not identify substantive psychological constructs.
This is distinct from the empirical manuscript dataset wsmed_examples().
example_dataexample_data
A tibble (data frame) with 100 rows and 14 variables:
Numeric measurements for variable A at three conditions.
Numeric measurements for variable B at three conditions.
Numeric measurements for variable C at three conditions.
Numeric measurements for variable D at three conditions.
An unordered factor with levels high, med, and low, in that order.
An unordered factor with levels high, med, and low, in that order.
All columns are complete. A wsMed analysis selects two condition columns per outcome or mediator. The factor labels are nominal categories; they do not request an ordinal regression model. Set their level order explicitly before fitting to select a different reference category.
wsmed_examples(), wsmed_categorical
data(example_data) dim(example_data) levels(example_data$Group)data(example_data) dim(example_data) levels(example_data$Group)
Dynamically generates a structural equation modeling (SEM) syntax for chained mediation analysis based on the prepared dataset. The function computes regression equations for mediators and the outcome variable, indirect effects along multi-step mediation paths, total effects, contrasts between indirect effects, and coefficients in different conditions.
GenerateModelCN(prepared_data, MP = character(0))GenerateModelCN(prepared_data, MP = character(0))
prepared_data |
A data frame returned by |
MP |
A character vector specifying which paths are moderated by variable(s) W.
Valid entries include:
- The function detects and inserts the correct interaction terms (e.g., \code{int_M2diff_W1}) based on these labels.
|
This function is used to construct SEM models for chained mediation analysis. It automatically parses variable names from the prepared dataset and dynamically creates the necessary model syntax, including:
Outcome regression: Defines the relationship between the difference scores of
the outcome (Ydiff) and the mediators (Mdiff) as well as their average scores (Mavg).
Mediator regressions: Defines the sequential regression models for each mediator's difference score, incorporating prior mediators as predictors.
Indirect effects: Computes the indirect effects along all possible multi-step mediation paths using the product of path coefficients.
Total indirect effect: Calculates the sum of all indirect effects from the chained mediation paths.
Total effect: Combines the direct effect (cp) and the total indirect effect.
Contrasts of indirect effects: Optionally calculates the pairwise contrasts between the indirect effects for different mediation paths.
Coefficients in different 'X' conditions: Calculates path coefficients in different X
conditions to observe the moderation effect of X.
This model is suitable for chained mediation designs where mediators influence each other in a sequential manner, forming multi-step mediation paths.
A character string representing the SEM model syntax for the specified chained mediation analysis.
When a moderated path starts at an endogenous mediator, auxiliary product
moment equations and covariances with its upstream disturbances preserve the
joint predictor moment structure under reference recoding. These equations
are not additional mediation paths. Genuine exogenous moments follow the
fitting function's fixed.x setting; endogenous product moments are estimated.
PrepareData(), wsMed(), GenerateModelP()
# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelCN(prepared_data) cat(sem_model)# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelCN(prepared_data) cat(sem_model)
Dynamically generates a structural equation modeling (SEM) syntax for combined parallel and chained mediation analysis based on the prepared dataset. The function computes regression equations for mediators and the outcome variable, indirect effects for both parallel and chained mediation paths, total effects, contrasts between indirect effects, and coefficients in different X conditions.
GenerateModelCP(prepared_data, MP = character(0))GenerateModelCP(prepared_data, MP = character(0))
prepared_data |
A data frame returned by |
MP |
A character vector specifying which paths are moderated by variable(s) W.
Acceptable values include:
- Each entry triggers inclusion of W’s main effect or interaction terms (e.g., \code{int_Mdiff_W}).
|
This function is used to construct SEM models that combine parallel and chained mediation analysis. It automatically parses variable names from the prepared dataset and dynamically creates the necessary model syntax, including:
Outcome regression: Defines the relationship between the difference scores of
the outcome (Ydiff), the chained mediator (M1diff), and the parallel mediators (M2diff, M3diff, etc.).
Mediator regressions: Defines the sequential regression models for the chained mediator and each parallel mediator.
Indirect effects: Computes the indirect effects for both chained and parallel mediation paths, including multi-step indirect effects involving both chained and parallel mediators.
Total indirect effect: Calculates the sum of all indirect effects from chained and parallel mediation paths.
Total effect: Combines the direct effect (cp) and the total indirect effect.
Contrasts of indirect effects: Optionally calculates the pairwise contrasts between the indirect effects for different mediation paths.
Coefficients in different 'X' conditions: Calculates path coefficients in different X
conditions to observe the moderation effect of X.
This model is suitable for designs where mediators include both a sequential chain (chained mediation) and independent parallel mediators.
A character string representing the SEM model syntax for the specified combined parallel and chained mediation analysis.
When a moderated path starts at an endogenous mediator, auxiliary product
moment equations and covariances with its upstream disturbances preserve the
joint predictor moment structure under reference recoding. These equations
are not additional mediation paths. Genuine exogenous moments follow the
fitting function's fixed.x setting; endogenous product moments are estimated.
PrepareData(), wsMed(), GenerateModelP(), GenerateModelCN()
# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelCP(prepared_data) cat(sem_model)# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelCP(prepared_data) cat(sem_model)
Generates lavaan model syntax for a user-defined within-subject mediation model. Users specify directed paths among mediators and from mediators to the outcome. The function automatically adds the corresponding difference and level components and identifies all indirect effects.
GenerateModelCustom(prepared_data, paths, MP = character(0))GenerateModelCustom(prepared_data, paths, MP = character(0))
prepared_data |
A data frame returned by |
paths |
A character vector defining directed paths among mediators
and from mediators to the outcome. For example:
|
MP |
A character vector identifying moderated paths. Supported
labels follow the existing wsMed convention:
Main effects of W are always labeled and used for conditional intercepts, including when a/cp is not explicitly listed in MP. |
A character string containing lavaan model syntax.
When a moderated path starts at an endogenous mediator, auxiliary product
moment equations and covariances with its upstream disturbances preserve the
joint predictor moment structure under reference recoding. These equations
are not additional mediation paths. Genuine exogenous moments follow the
fitting function's fixed.x setting; endogenous product moments are estimated.
prepared_data <- data.frame( M1diff = rnorm(100), M1avg = rnorm(100), M2diff = rnorm(100), M2avg = rnorm(100), M3diff = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) model <- GenerateModelCustom( prepared_data = prepared_data, paths = c( "M1 -> M3", "M1 -> Y", "M3 -> Y", "M2 -> Y" ) ) cat(model)prepared_data <- data.frame( M1diff = rnorm(100), M1avg = rnorm(100), M2diff = rnorm(100), M2avg = rnorm(100), M3diff = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) model <- GenerateModelCustom( prepared_data = prepared_data, paths = c( "M1 -> M3", "M1 -> Y", "M3 -> Y", "M2 -> Y" ) ) cat(model)
Dynamically generates a structural equation modeling (SEM) syntax for parallel mediation analysis based on the prepared dataset. The function computes regression equations for mediators and the outcome variable, indirect effects, total effects, contrasts between indirect effect, and .
GenerateModelP(prepared_data, MP = character(0))GenerateModelP(prepared_data, MP = character(0))
prepared_data |
A data frame returned by |
MP |
A character vector specifying which paths are moderated by variable(s) W.
Valid values include:
- This argument controls which interaction terms (e.g., \code{int_Mdiff_W}, \code{int_Mavg_W}) are
added to the corresponding regression equations.
|
This function is used to construct SEM models for parallel mediation analysis. It automatically parses variable names from the prepared dataset and dynamically creates the necessary model syntax, including:
Outcome regression: Defines the relationship between the difference scores of
the outcome (Ydiff) and the mediators (Mdiff) as well as their average scores (Mavg).
Mediator regressions: Defines the intercept models for each mediator's difference score.
Indirect effects: Computes the indirect effects for each mediator using the
product of path coefficients (e.g., a * b).
Total indirect effect: Calculates the sum of all indirect effects.
Total effect: Combines the direct effect (cp) and the total indirect effect.
Contrasts of indirect effects: Optionally calculates the pairwise contrasts between the indirect effects when multiple mediators are present.
coefficients in different 'X' conditions: Calculates path coefficients in different X conditions to observe the moderation effect of ‘X'.
This model is suitable for parallel mediation designs where multiple mediators act independently.
A character string representing the SEM model syntax for the specified parallel mediation analysis.
When a moderated path starts at an endogenous mediator, auxiliary product
moment equations and covariances with its upstream disturbances preserve the
joint predictor moment structure under reference recoding. These equations
are not additional mediation paths. Genuine exogenous moments follow the
fitting function's fixed.x setting; endogenous product moments are estimated.
PrepareData(), wsMed(), GenerateModelCN()
# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelP(prepared_data) cat(sem_model)# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelP(prepared_data) cat(sem_model)
Dynamically generates a structural equation modeling (SEM) syntax for
mediation analysis that integrates both parallel and chained mediators. Unlike the
Combined Parallel and Chained mediation model (GenerateModelCP), this function assumes
that the chained mediator receives inputs from the parallel mediators and directly influences
the outcome variable, emphasizing a downstream role for the chained mediator.
GenerateModelPC(prepared_data, MP = character(0))GenerateModelPC(prepared_data, MP = character(0))
prepared_data |
A data frame returned by |
MP |
A character vector specifying which paths are moderated by variable(s) W.
Acceptable values include:
- This argument controls which interaction terms (e.g., \code{int_Mdiff_W}, \code{int_Mavg_W}) are included
in the regression equations. Variable names are automatically matched using the naming convention
\code{"int_<predictor>_W<index>"}.
|
This function is designed to build SEM models that integrate parallel and chained mediation structures. It automatically identifies variable names from the prepared dataset and generates the necessary model syntax, including:
Outcome regression: Defines the relationship between the difference scores of the outcome (Ydiff),
the chained mediator (M1diff), and the parallel mediators (M2diff, M3diff, etc.).
Mediator regressions: Constructs separate regression models for the parallel mediators and the chained mediator. The chained mediator incorporates predictors from all parallel mediators.
Indirect effects: Computes indirect effects for:
Parallel mediators (M2diff, M3diff, etc.) directly influencing the outcome.
The chained mediator (M1diff) directly influencing the outcome.
Combined paths where parallel mediators influence the chained mediator, which in turn influences the outcome.
Total indirect effect: Summarizes all indirect effects from parallel and chained mediation paths.
Total effect: Combines the direct effect (cp) and the total indirect effect.
Contrasts of indirect effects: Optionally computes pairwise contrasts between indirect effects for different mediation paths.
Coefficients in different 'X' conditions: Computes path coefficients under different X conditions
to analyze moderation effects.
This model is suitable for designs where mediators include both independent parallel paths and sequential chained paths, providing a comprehensive mediation analysis framework.
A character string representing the SEM model syntax for the specified parallel and chained mediation analysis.
When a moderated path starts at an endogenous mediator, auxiliary product
moment equations and covariances with its upstream disturbances preserve the
joint predictor moment structure under reference recoding. These equations
are not additional mediation paths. Genuine exogenous moments follow the
fitting function's fixed.x setting; endogenous product moments are estimated.
PrepareData(), wsMed(), GenerateModelP(), GenerateModelCN()
# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelPC(prepared_data) cat(sem_model)# Example prepared data prepared_data <- data.frame( M1diff = rnorm(100), M2diff = rnorm(100), M3diff = rnorm(100), M1avg = rnorm(100), M2avg = rnorm(100), M3avg = rnorm(100), Ydiff = rnorm(100) ) # Generate SEM model syntax sem_model <- GenerateModelPC(prepared_data) cat(sem_model)
The ImputeData function performs multiple imputation on a data frame with missing values using the mice package. It handles missing data by creating multiple imputed datasets based on a specified imputation method and returns a list of completed data frames.
ImputeData( data_missing, m = 5, method = "pmm", seed = 123, predictorMatrix = NULL )ImputeData( data_missing, m = 5, method = "pmm", seed = 123, predictorMatrix = NULL )
data_missing |
A data frame containing missing values to be imputed. The function replaces values coded as |
m |
An integer specifying the number of imputed datasets to generate. |
method |
A character string specifying the imputation method. Default is |
seed |
An integer for setting the random seed to ensure reproducibility. Default is |
predictorMatrix |
An optional matrix specifying the predictor structure for the imputation model. Default is |
This function replaces specified missing value placeholders (e.g., -999) with NA, and then applies the multiple imputation by chained equations (MICE) procedure to generate multiple imputed datasets. It supports flexible imputation methods and allows for specifying a custom predictor matrix.
A list of m imputed data frames.
Wendie Yang, Shufai Cheung
# Example data with missing values data <- data.frame( M1 = c(rnorm(99), rep(NA, 1)), M2 = c(rnorm(99), rep(NA, 1)), Y1 = rnorm(100), Y2 = rnorm(100) ) # Perform multiple imputation imputed_data_list <- ImputeData(data, m = 5) # Display the first imputed dataset head(imputed_data_list[[1]])# Example data with missing values data <- data.frame( M1 = c(rnorm(99), rep(NA, 1)), M2 = c(rnorm(99), rep(NA, 1)), Y1 = rnorm(100), Y2 = rnorm(100) ) # Perform multiple imputation imputed_data_list <- ImputeData(data, m = 5) # Display the first imputed dataset head(imputed_data_list[[1]])
Computes Monte Carlo confidence intervals (MCCI) for structural equation models (SEM) fitted to multiple imputed datasets. This function integrates SEM fitting across imputed datasets, pools the results, and generates confidence intervals through Monte Carlo sampling.
MCMI2( sem_model, imputations, R = 20000L, alpha = c(0.001, 0.01, 0.05), decomposition = "eigen", pd = TRUE, tol = 1e-06, seed = NULL, estimator = "ML", se = "standard", missing = "listwise", fixed.x = FALSE )MCMI2( sem_model, imputations, R = 20000L, alpha = c(0.001, 0.01, 0.05), decomposition = "eigen", pd = TRUE, tol = 1e-06, seed = NULL, estimator = "ML", se = "standard", missing = "listwise", fixed.x = FALSE )
sem_model |
A character string specifying the SEM model syntax. |
imputations |
A list of data frames, where each data frame represents an imputed dataset. |
R |
An integer specifying the number of Monte Carlo samples. Default is |
alpha |
A numeric vector specifying significance levels for the confidence intervals. Default is |
decomposition |
A character string specifying the decomposition method for the covariance matrix.
Default is |
pd |
A logical value indicating whether to ensure positive definiteness of the covariance matrix. Default is |
tol |
A numeric value specifying the tolerance for positive definiteness checks. Default is |
seed |
An optional integer specifying the random seed for reproducibility. Default is |
estimator |
A character string specifying the estimator for SEM fitting. Default is |
se |
A character string specifying the type of standard errors to compute. Default is |
missing |
A character string specifying the method for handling missing data in SEM fitting. Default is |
fixed.x |
Whether exogenous covariates are treated as fixed in every imputation. Defaults to FALSE, consistently with wsMed(). |
This function is designed for SEM models that require multiple imputation to handle missing data. It performs the following steps:
SEM Fitting: Fits the specified SEM model to each imputed dataset using lavaan::sem().
Pooling Results: Combines parameter estimates and covariance matrices across imputations using Rubin's rules.
Monte Carlo Sampling: Generates Monte Carlo samples based on the pooled estimates and covariance matrices, and calculates confidence intervals for model parameters.
This function supports custom estimators, handling of missing data, and precision adjustments for Monte Carlo sampling. It is particularly useful for mediation analysis or complex SEM models where missing data are addressed using multiple imputation.
With decomposition = "eigen", Monte Carlo sampling uses the
principal symmetric covariance square root. Equivalent eigenvector signs
and repeated-eigenvalue bases therefore produce the same draws up to numerical
precision. Fixed-seed draws differ from wsMed 1.1.0; the target distribution
and pooled point estimates are unchanged. Reproducing the complete analysis
also requires matching data, imputation settings, and software dependencies.
An object of class semmcci containing:
call: The matched function call.
args: A list of input arguments.
thetahat: The pooled parameter estimates.
thetahatstar: Monte Carlo samples for parameter estimates.
fun: The name of the function ("MCMI2").
lavaan::sem(), semmcci::MC(), semmcci::MCStd()
# Example SEM model sem_model <- " Ydiff ~ b1 * M1diff + cp * 1 M1diff ~ a1 * 1 indirect := a1 * b1 total := cp + indirect " # Example imputed datasets imputations <- list( data.frame(M1diff = rnorm(100), Ydiff = rnorm(100)), data.frame(M1diff = rnorm(100), Ydiff = rnorm(100)) ) # Compute Monte Carlo confidence intervals result <- MCMI2( sem_model = sem_model, imputations = imputations, R = 1000, alpha = c(0.05, 0.01), seed = 123 )# Example SEM model sem_model <- " Ydiff ~ b1 * M1diff + cp * 1 M1diff ~ a1 * 1 indirect := a1 * b1 total := cp + indirect " # Example imputed datasets imputations <- list( data.frame(M1diff = rnorm(100), Ydiff = rnorm(100)), data.frame(M1diff = rnorm(100), Ydiff = rnorm(100)) ) # Compute Monte Carlo confidence intervals result <- MCMI2( sem_model = sem_model, imputations = imputations, R = 1000, alpha = c(0.05, 0.01), seed = 123 )
Draw point estimates and confidence intervals by categorical group or by the stored low, mean and high levels of a continuous moderator. Each effect is shown in its own panel. Categories are not joined by interpolating lines.
plot_conditional_effects( result, paths = NULL, type = c("indirect", "paths", "overall"), levels = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12, ncol = NULL )plot_conditional_effects( result, paths = NULL, type = c("indirect", "paths", "overall"), levels = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12, ncol = NULL )
result |
A result returned by |
paths |
Optional character vector of effect identifiers, in display
order. NULL selects all available effects. Both |
type |
|
levels |
Optional group/level labels to select, in display order.
NULL uses their stored order. For continuous W the labels are |
standardized |
Use standardized results, requested when fitting with
|
engine |
For |
labels |
Optional named character vector mapping effect identifiers to display labels. Partial mappings are allowed. |
title |
Optional plot title. |
x_label, y_label
|
Optional axis labels. |
base_size |
Base font size. |
ncol |
Optional number of facet columns. |
Intervals are the stored percentile conditional intervals, including jointly transformed scales for standardized results. They are individual intervals, not simultaneous confidence intervals.
A ggplot object with plotted data and a wsmed_plot attribute.
plot_effects(), plot_contrasts()
Draw contrast estimates and their confidence intervals relative to zero. With a moderator, contrasts compare groups or stored moderator levels within each effect. Without a moderator, specific indirect paths are compared with one another. The displayed subtraction order is explicit.
plot_contrasts( result, paths = NULL, type = c("indirect", "paths", "overall"), contrasts = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12, ncol = NULL )plot_contrasts( result, paths = NULL, type = c("indirect", "paths", "overall"), contrasts = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12, ncol = NULL )
result |
A result returned by |
paths |
Optional character vector of effect identifiers, in display
order. NULL selects all available effects. Both |
type |
|
contrasts |
Optional exact contrast labels to select, in display order.
NULL selects all. Inspect the corresponding result table or the returned
plot's |
standardized |
Use standardized results, requested when fitting with
|
engine |
For |
labels |
Optional named character vector mapping effect identifiers to display labels. Partial mappings are allowed. |
title |
Optional plot title. |
x_label, y_label
|
Optional axis labels. |
base_size |
Base font size. |
ncol |
Optional number of facet columns. |
Moderator contrasts use the existing joint-draw contrast tables.
Without a moderator, only type = "indirect" is available: contrasts
are computed from the stored joint draws, with point estimates evaluated
at fitted/pooled parameters. Their intervals are percentile intervals.
Standardized draws use the same draw-specific marginal endpoint scales
as other standardized effects. No model is refitted. Interval endpoints
for two separate effects are never subtracted to construct a contrast CI.
paths and labels apply to effect panels when a moderator is present;
without a moderator, paths selects the indirect effects to compare and
labels maps the full contrast labels. Continuous overall contrasts are
unavailable when the fitted result does not contain that contrast table.
A ggplot object with plotted data and a wsmed_plot attribute.
plot_effects(), plot_conditional_effects()
Plot fitted indirect effects, the total indirect effect, the direct effect
(cp) and the total effect with their stored confidence intervals.
With a moderator these are effects at the model's reference value (centered
continuous W = 0, or the reference category), not averages across W.
Use plot_conditional_effects() to show selected moderator levels instead.
plot_effects( result, paths = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12 )plot_effects( result, paths = NULL, standardized = FALSE, engine = c("mc", "boot"), labels = NULL, title = NULL, x_label = NULL, y_label = NULL, base_size = 12 )
result |
A result returned by |
paths |
Optional character vector of effect identifiers, in display
order. NULL selects all available effects. Both |
standardized |
Use standardized results, requested when fitting with
|
engine |
For |
labels |
Optional named character vector mapping effect identifiers to display labels. Partial mappings are allowed. |
title |
Optional plot title. |
x_label, y_label
|
Optional axis labels. |
base_size |
Base font size. |
MC intervals come from the parameter draws (or the stored
standardized parameter table). Bootstrap plots use the bootstrap limits,
not the normal-theory limits that may also be present in the table.
New workflow objects use wsmed_plots. Both interfaces expose full-precision
estimate, conf.low, and conf.high columns in the plotted data; legacy
column names remain available. Interval conventions are not silently changed.
A ggplot object. Its data contains the plotted estimates and
CI.LL/CI.UL limits. The wsmed_plot attribute records the selected
engine, scale and confidence level. Use ggplot2::ggsave() to export it.
plot_conditional_effects(), plot_contrasts(),
plot_moderation_curve()
Plot a conditional indirect effect, total effect or path coefficient with its pointwise confidence band. Highlight stored grid values whose interval excludes zero. Boundary labels use raw moderator units, not sample percentiles.
plot_moderation_curve( result, path_name, title = NULL, x_label = "Moderator (W, raw units)", y_label = "Estimate", ns_fill = "#FEE0D2", sig_fill = "#C7E9C0", alpha_ci = 0.35, alpha_sig = 0.35, base_size = 14, standardized = FALSE, engine = c("mc", "boot") )plot_moderation_curve( result, path_name, title = NULL, x_label = "Moderator (W, raw units)", y_label = "Estimate", ns_fill = "#FEE0D2", sig_fill = "#C7E9C0", alpha_ci = 0.35, alpha_sig = 0.35, base_size = 14, standardized = FALSE, engine = c("mc", "boot") )
result |
A result returned by |
path_name |
One stored effect identifier, such as
|
title |
Optional plot title. |
x_label, y_label
|
Axis labels. The default x axis uses raw W units. |
ns_fill |
Colour of the complete confidence band. |
sig_fill |
Colour of the regions whose pointwise CI excludes zero. |
alpha_ci, alpha_sig
|
Opacity of the band and highlighted regions. |
base_size |
Base font size. |
standardized |
Use the stored standardized conditional results. |
engine |
For |
Highlighted intervals are approximate ranges on the stored grid,
not exact Johnson–Neyman boundaries or simultaneous confidence regions.
A label [a, b] reports the first and last qualifying grid values. An
isolated qualifying point is marked by a vertical line. Missing confidence
limits break a highlighted range. The displayed confidence level follows
result$alpha; no fixed p-value threshold is implied.
A ggplot object. Its data contains the selected curve;
the wsmed_regions attribute contains raw-unit grid interval endpoints.
The wsmed_plot attribute records engine, scale and confidence level.
plot_effects(), plot_conditional_effects(), plot_contrasts()
PrepareData() transforms raw pre/post data into the set of variables
required by the wsMed workflow.
It handles mediators, outcome, within-subject controls, between-subject
controls, moderators, and all necessary interaction terms, while
automatically centering / dummy-coding variables as needed.
PrepareData( data, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, center_W = TRUE, keep_W_raw = TRUE, keep_C_raw = TRUE )PrepareData( data, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, center_W = TRUE, keep_W_raw = TRUE, keep_C_raw = TRUE )
data |
A data frame with the raw pre/post measures. |
M_C1, M_C2
|
Character vectors: mediator names at occasion 1 and 2 (equal length). |
Y_C1, Y_C2
|
Character scalars: outcome names at occasion 1 and 2. |
C_C1, C_C2
|
Optional character vectors: within-subject control names. |
C |
Optional character vector: between-subject control names. |
C_type |
Optional vector of the same length as |
W |
Optional character scalar: one moderator column name. |
W_type |
Optional vector of the same length as |
center_W |
Logical. Whether to center the moderator variable |
keep_W_raw, keep_C_raw
|
Logical. If |
The function performs the following steps:
Outcome difference: Ydiff = Y_C2 - Y_C1.
Mediator variables for each pair (M_C1[i], M_C2[i]):
Mi_diff = M_C2 - M_C1
Mi_avg is the mean-centered average of the two occasions.
Between-subject controls C:
Continuous variables are grand-mean centered (Cb1, Cb2, ...).
Categorical variables (binary or multi-level) are expanded into k - 1
dummy variables (Cb1_1, Cb2_1, Cb2_2, ...), using the
first level as the reference.
Within-subject controls Cw: difference and centered-average versions
(Cw1diff, Cw1avg, ...).
Moderator W (at most one):
Continuous variables are grand-mean centered (W1, W2, ...).
Categorical variables are dummy-coded in the same way as C.
Interaction terms between each moderator column and each mediator column:
int_<Mi_diff>_<Wj>, int_<Mi_avg>_<Wj>.
Two attributes are added to the returned data:
"W_info": raw names, dummy names, level mapping
"C_info": same structure for between-subject controls.
Row counts are preserved even if input factors contain NA values
(model.matrix is called with na.action = na.pass).
A data frame containing at minimum:
Ydiff
Mi_diff, Mi_avg for each mediator
centered or dummy-coded Cb*, Cw*diff, Cw*avg
centered or dummy-coded W* and all int_* interaction terms
plus the attributes "W_info" and "C_info" described above.
PrepareMissingData, GenerateModelP,
wsMed, wsmed_categorical
set.seed(1) raw <- data.frame( A1 = rnorm(50), A2 = rnorm(50), # mediator 1 B1 = rnorm(50), B2 = rnorm(50), # mediator 2 C1 = rnorm(50), C2 = rnorm(50), # outcome D1 = rnorm(50), D2 = rnorm(50), # within-subject control W_bin = sample(0:1, 50, TRUE), # between-subject binary C W_fac3 = factor(sample(c("Low","Med","High"), 50, TRUE)) # moderator W ) prep <- PrepareData( data = raw, M_C1 = c("A1","B1"), M_C2 = c("A2","B2"), Y_C1 = "C1", Y_C2 = "C2", C_C1 = "D1", C_C2 = "D2", C = "W_bin", C_type = "categorical", W = "W_fac3", W_type = "categorical" ) head(prep)set.seed(1) raw <- data.frame( A1 = rnorm(50), A2 = rnorm(50), # mediator 1 B1 = rnorm(50), B2 = rnorm(50), # mediator 2 C1 = rnorm(50), C2 = rnorm(50), # outcome D1 = rnorm(50), D2 = rnorm(50), # within-subject control W_bin = sample(0:1, 50, TRUE), # between-subject binary C W_fac3 = factor(sample(c("Low","Med","High"), 50, TRUE)) # moderator W ) prep <- PrepareData( data = raw, M_C1 = c("A1","B1"), M_C2 = c("A2","B2"), Y_C1 = "C1", Y_C2 = "C2", C_C1 = "D1", C_C2 = "D2", C = "W_bin", C_type = "categorical", W = "W_fac3", W_type = "categorical" ) head(prep)
Handles missing values in the dataset through multiple imputation and prepares the imputed datasets for within-subject mediation analysis. The function imputes missing data, processes each imputed dataset, and provides diagnostics for the imputation process.
PrepareMissingData( data_missing, m = 5, method_num = "pmm", seed = 123, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, center_W = TRUE, keep_W_raw = TRUE, keep_C_raw = TRUE )PrepareMissingData( data_missing, m = 5, method_num = "pmm", seed = 123, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, center_W = TRUE, keep_W_raw = TRUE, keep_C_raw = TRUE )
data_missing |
A data frame containing the raw dataset with missing values. |
m |
An integer specifying the number of imputations to perform. Default is |
method_num |
Character; imputation method for numeric variables
(for example, |
seed |
An integer specifying the random seed for reproducibility. Default is |
M_C1 |
A character vector of column names representing mediators at condition 1. |
M_C2 |
A character vector of column names representing mediators at condition 2.
Must match the length of |
Y_C1 |
A character string representing the column name of the outcome variable at condition 1. |
Y_C2 |
A character string representing the column name of the outcome variable at condition 2. |
C_C1 |
Character vector of within-subject control variable names (condition 1). |
C_C2 |
Character vector of within-subject control variable names (condition 2). |
C |
Character vector of between-subject control variable names. |
C_type |
Optional vector of the same length as |
W |
A character vector specifying the names of moderator variables
that are used to generate interaction terms with mediators. These variables
will be included in the imputation model and passed to |
W_type |
Optional vector of the same length as |
center_W |
Logical. Whether to center the moderator variable W. |
keep_W_raw, keep_C_raw
|
Logical; keep the original W / C columns in the returned data? |
This function is designed to preprocess datasets with missing values for mediation analysis. It performs the following steps:
Multiple imputation: Uses specified imputation methods
(for example, predictive mean matching) to generate
m imputed datasets.
Data preparation: Applies PrepareData to each of the
m imputed datasets to calculate difference scores
and centered averages for mediators and the outcome variable.
Imputation diagnostics: Provides summary diagnostics for the imputation process, including information about missing data patterns and convergence.
This function integrates imputation and data preparation, ensuring that the resulting datasets are ready for subsequent mediation analysis.
A list containing:
processed_data_listA list of m data frames,
each representing an imputed and processed dataset ready for
within-subject mediation analysis.
imputation_summaryA summary of the imputation process, including diagnostics and convergence information.
PrepareData, ImputeData, wsMed
# Example dataset with missing values data("example_data", package = "wsMed") set.seed(123) example_dataN <- mice::ampute( data = example_data, prop = 0.1 )$amp # Prepare the dataset with multiple imputations prepared_missing_data <- PrepareMissingData( data_missing = example_dataN, m = 5, M_C1 = c("A2", "B2"), M_C2 = c("A1", "B1"), Y_C1 = "C2", Y_C2 = "C1" ) # Access processed datasets processed_data_list <- prepared_missing_data$processed_data_list imputation_summary <- prepared_missing_data$imputation_summary# Example dataset with missing values data("example_data", package = "wsMed") set.seed(123) example_dataN <- mice::ampute( data = example_data, prop = 0.1 )$amp # Prepare the dataset with multiple imputations prepared_missing_data <- PrepareMissingData( data_missing = example_dataN, m = 5, M_C1 = c("A2", "B2"), M_C2 = c("A1", "B1"), Y_C1 = "C2", Y_C2 = "C1" ) # Access processed datasets processed_data_list <- prepared_missing_data$processed_data_list imputation_summary <- prepared_missing_data$imputation_summary
Formats and prints the SEM model syntax generated by
GenerateModelCN, GenerateModelCP, GenerateModelP, and GenerateModelPC.
It organizes the equations into labeled sections for better readability.
printGM(x, ...)printGM(x, ...)
x |
A list or character string containing SEM model syntax.
If |
... |
Additional arguments (not used). |
Invisibly returns the formatted SEM model syntax.
data(example_data) head(example_data) prepared_data <- PrepareData( data = example_data, M_C1 = c("A1", "B1"), M_C2 = c("A2", "B2"), Y_C1 = "C1", Y_C2 = "C2" ) sem_model <- GenerateModelPC(prepared_data) printGM(sem_model)data(example_data) head(example_data) prepared_data <- PrepareData( data = example_data, M_C1 = c("A1", "B1"), M_C2 = c("A2", "B2"), Y_C1 = "C1", Y_C2 = "C2" ) sem_model <- GenerateModelPC(prepared_data) printGM(sem_model)
Standardize conditional mediation results using existing joint draws
standardize_moderation(object)standardize_moderation(object)
object |
A wsMed result with a moderator and stored MC or bootstrap draws. |
Conditional indirect and total effects are divided by the marginal model-implied SD of Ydiff. Conditional paths use their endpoint scales. Moderator probe values remain fixed in raw units; continuous interaction coefficients in mod_coeff are reported per SD of W. Dummy variables retain 0/1 units. Coefficients and scales are transformed jointly for each draw. Intervals are percentile intervals, as in the raw conditional tables. Metadata attributes record scales, probe conventions and draw diagnostics. With fixed.x=TRUE, external moments are held fixed. MI uses pooled primitive parameters and the existing first-imputation probing reference. For models with endogenous products, marginal variances are pooled jointly with coefficients before taking square roots, retaining their sampling covariance. Saved endogenous-product fits and MI draws require compatible algorithm identifiers. Refit unversioned old models rather than restandardizing them.
A moderation list with the same conditional tables and curves as the raw output, or a list with mc and boot components for ci_method="both".
wsMed() fits a structural equation model (SEM) for two-condition
within-subject mediation. It can handle missing data (DE, FIML, MI) and
computes both unstandardized and standardized effects with bootstrap or
Monte Carlo confidence intervals.
wsMed( data, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, MP = NULL, form = c("P", "CN", "CP", "PC", "UD"), Na = c("DE", "FIML", "MI"), alpha = 0.05, mi_args = list(), R = 20000L, bootstrap = 2000, boot_ci_type = "perc", iseed = 123, fixed.x = FALSE, ci_method = c("mc", "bootstrap", "both"), MCmethod = NULL, seed = 123, standardized = FALSE, verbose = FALSE, paths = NULL )wsMed( data, M_C1, M_C2, Y_C1, Y_C2, C_C1 = NULL, C_C2 = NULL, C = NULL, C_type = NULL, W = NULL, W_type = NULL, MP = NULL, form = c("P", "CN", "CP", "PC", "UD"), Na = c("DE", "FIML", "MI"), alpha = 0.05, mi_args = list(), R = 20000L, bootstrap = 2000, boot_ci_type = "perc", iseed = 123, fixed.x = FALSE, ci_method = c("mc", "bootstrap", "both"), MCmethod = NULL, seed = 123, standardized = FALSE, verbose = FALSE, paths = NULL )
data |
A data.frame containing the raw scores. |
M_C1, M_C2
|
Character vectors of mediator names under condition 1 and 2. |
Y_C1, Y_C2
|
Character scalars for the outcome under each condition. |
C_C1, C_C2
|
Character vectors of within-subject covariates (per condition). |
C |
Character vector of between-subject covariates. |
C_type |
Character; type of |
W |
Character vector of moderators. Default |
W_type |
Character; |
MP |
Character vector identifying which regression paths are moderated
(for example, |
form |
Model type: |
Na |
Missing-data method: |
alpha |
Numeric vector in (0, 1); two-sided significance levels. |
mi_args |
List of MI-specific controls:
|
R |
Integer; number of Monte Carlo draws. Default |
bootstrap |
Integer; number of bootstrap replicates (DE and FIML only). |
boot_ci_type |
Character; CI type for stored legacy bootstrap parameter
tables: |
iseed, seed
|
Integer seeds for bootstrap and Monte Carlo, respectively. |
fixed.x |
Logical; passed to lavaan. |
ci_method |
CI engine: |
MCmethod |
NULL or |
standardized |
Logical; if |
verbose |
Logical; print progress messages. |
paths |
A character vector defining directed paths when
|
Model structures:
"P": parallel mediation
"CN": chained (serial) mediation
"CP": chained then parallel
"PC": parallel then chained
"UD": user-defined mediation model
Missing-data strategies:
"DE": list-wise deletion
"FIML": full-information maximum likelihood
"MI": multiple imputation via mice
Confidence-interval engines:
Bootstrap: participant resampling (DE and FIML only)
Monte Carlo: joint parameter draws via semmcci for DE/FIML, or the package's pooled-parameter sampler for MI
Monte Carlo inference uses the existing joint-parameter sampler. The legacy
MCmethod = "bootSD" option was accepted but never applied; it now
produces an explicit error rather than silently returning ordinary MC results.
Standardization divides differences by their marginal model-implied SDs, without recentering them. Dummy variables retain 0/1 units; interaction terms use the product of their component scale factors, not the interaction column SD. MC and bootstrap draws are transformed jointly with their scales. Current effect reports from print, summary and wsmed_effects, and confint applied to extracted effects, use percentile intervals (type-7 quantiles), with or without moderation. The boot_ci_type argument controls stored legacy parameter-table intervals, not these effect reports. In standardized legacy tables, bc and bca.simple apply bias correction with zero acceleration, not full BCa. Their bootstrap p-values require at least 1000 valid replicates.
Conditional tables use percentile intervals and fixed numerical probes. With fixed.x=TRUE, scale transformations condition on the fitted external moments rather than adding sampling uncertainty for those moments. In MI, probes/centering references use the first completed data set; fixed.x=TRUE also conditions on its external moments in the pooled transform. In MI models with products of mediator differences and the moderator, marginal variances are pooled jointly with primitive coefficients, including their delta-method within-imputation and Rubin between-imputation covariance. MC propagates this joint uncertainty. Endogenous product moments are estimated even with fixed.x=TRUE.
Workflow: (1) preprocess -> (2) generate SEM syntax -> (3) fit -> (4) compute confidence intervals -> (5) optional: standardize estimates. See wsmed_categorical for supported categorical predictors, reference coding, and missing-data restrictions. In both interfaces, declare categorical covariates and moderators as unordered factors with explicit levels before fitting. The first factor level is the reference group. Existing automatic recognition of numeric 0/1 predictors is retained in this one-call interface. The empirical manuscript dataset is available as wsmed_examples; example_data is simulated tutorial data.
The one-call interface uses the same fitting and inference engines
as wsmed_model(), wsmed_fit(), and wsmed_infer(). Default printing is
concise; print(result, detail = "full") adds path coefficients to
the structured effect report. Use detail = "legacy" for the original
tables.
Use wsmed_effects() to query stored draws without rerunning the analysis.
An object of class "wsMed" with elements:
Preprocessed data frame.
Generated lavaan syntax.
List with Monte Carlo draws, bootstrap tables (if any), and the fitted model.
Raw conditional or moderated effect tables.
Standardized conditional tables and curves when standardized=TRUE and a moderator is supplied.
Analysis settings.
The user-defined paths when form = "UD";
otherwise NULL.
Names of all user-supplied variables.
Structured specification, reusable fit (including all imputation fits), and named stored inference objects.
data("example_data", package = "wsMed") result <- wsMed( data = example_data, M_C1 = c("A1", "B1"), M_C2 = c("A2", "B2"), Y_C1 = "D1", Y_C2 = "D2" ) print(result)data("example_data", package = "wsMed") result <- wsMed( data = example_data, M_C1 = c("A1", "B1"), M_C2 = c("A2", "B2"), Y_C1 = "D1", Y_C2 = "D2" ) print(result)
wsMed supports binary and multicategory between-subject covariates and one categorical moderator in models with numeric outcomes and mediators.
Outcomes, mediators, and within-subject covariates must be numeric measures
analyzed by the continuous-response SEM. Binary or ordinal response models,
thresholds, and categorical links are not implemented. Storing a binary
outcome as numbers does not turn the estimator into a categorical-response
model. Between-subject covariates and the single moderator may instead be
unordered factors. Ordered factors are rejected by wsmed_fit(); explicitly
convert them to unordered factors only if a nominal interpretation is intended.
In both the one-call and staged workflows, use base::factor() to declare
categorical between-subject covariates and moderators in the input data.
Specify levels explicitly: the first level is the reference group. For a
binary predictor, factor(x, levels = c(0, 1)) selects 0 as the reference;
reversing the levels selects 1. Use unordered factors for nominal categories.
Every declared factor level must have observations in the supplied data.
The existing default recognition rules are retained for compatibility.
wsmed_fit() treats numeric predictors, including 0/1 columns, as continuous.
The one-call wsMed() and PrepareData() interfaces retain automatic
detection: factors, character columns, and numeric columns whose observed
values are exactly 0 and 1 are categorical. Other numeric columns are
continuous unless C_type or W_type overrides detection.
Explicit factors provide the same categorical interpretation and reference
coding in both interfaces without relying on automatic recognition. The
one-call type arguments remain available to override its default rules.
A factor with K levels is represented by K - 1 treatment indicators. The first
factor level is the reference; stats::relevel() changes it before fitting.
Indicators are not mean-centered. Coding does not depend on the global
contrasts option. Between-subject indicators use Cb* names and
moderator indicators use W* names. The C_info and W_info
attributes of prepared data record their mappings. Labels such as
low vs high identify the reference and comparison level: the indicator
is 0 at low and 1 at high, so its coefficient is high minus low.
wsmed_effects() accepts original factor labels in at; by default
it extracts every level. wsmed_contrasts() compares effects using their
joint draws, preserving covariance. Do not subtract the endpoints of
separate confidence intervals to obtain an interval for a difference.
Marginally standardized conditional effects use the common model-implied
outcome-difference SD, not separate within-category SDs; factor labels and
dummy indicators retain their coding. See standardize_moderation().
Generated models account for the dependence of endogenous products on upstream
mediator disturbances. Reference changes preserve the implied marginal scales
of the same fitted model. MI pools marginal variance estimates jointly with
coefficients; compare the same completed datasets when checking recoding.
Refit saved models from before this covariance correction.
The staged default missing = "error" rejects missing analysis values.
Listwise deletion and multiple imputation are available for incomplete
categorical predictors. FIML is allowed with fully observed categorical
predictors but wsmed_fit() rejects missing categorical predictors; the
one-call interface should follow the same restriction.
MI imputes the raw variables before constructing dummy variables and
interactions. The staged mi$method argument selects the method for
numeric variables (default "pmm"). Factors use logistic regression
for two levels and multinomial logistic regression for more than two levels.
This differs from the lower-level ImputeData() method argument.
MI supports Monte Carlo inference only.
wsmed_model(), wsmed_fit(), wsmed_effects(),
wsmed_contrasts(), PrepareData(), ImputeData()
data(example_data) dat <- example_data dat$Group <- factor(dat$Group, levels = c("low", "med", "high")) prepared <- PrepareData(dat, M_C1 = "A1", M_C2 = "A2", Y_C1 = "D1", Y_C2 = "D2", W = "Group", W_type = "categorical") attr(prepared, "W_info")data(example_data) dat <- example_data dat$Group <- factor(dat$Group, levels = c("low", "med", "high")) prepared <- PrepareData(dat, M_C1 = "A1", M_C2 = "A2", Y_C1 = "D1", Y_C2 = "D2", W = "Group", W_type = "categorical") attr(prepared, "W_info")
Contrast effects using their joint stored draws
wsmed_contrasts(object, contrasts, level = object$query$level)wsmed_contrasts(object, contrasts, level = object$query$level)
object |
A wsmed_results object, containing every effect to compare. |
contrasts |
Named list of named numeric weight vectors. Weight names must match the term column of as.data.frame(object). |
level |
Confidence level; defaults to the input result's level. |
A wsmed_results object. Intervals are percentile intervals of the jointly evaluated contrasts, not differences between confidence limits.
Extract effects from fitted models or stored inference
wsmed_effects( object, type = c("indirect", "all", "total", "direct", "total_indirect", "paths", "parameters"), terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, standardized = NULL )wsmed_effects( object, type = c("indirect", "all", "total", "direct", "total_indirect", "paths", "parameters"), terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, standardized = NULL )
object |
A wsmed_fit, wsmed_inference, or wsMed result. |
type |
Effect family: indirect, all (direct, specific indirect, total indirect and total effects), total, direct, total_indirect, paths, or parameters (primitive model parameters). |
terms |
Optional coefficient or effect names within the selected family. |
at |
Named list of raw moderator values, for example list(Age = c(30, 50)). Defaults to the centering reference for a continuous moderator, or all observed levels for a categorical moderator. Parameters ignore no probes: supplying at with type = "parameters" is an error. |
scale |
Compatibility spelling: raw or marginal. Explicit conflicting scale and standardized arguments are rejected. |
method |
Stored inference to use when object is wsMed: mc or bootstrap. Required if both are stored. A fit alone returns point estimates only. |
level |
Confidence level; defaults to the stored inference level or .95. |
standardized |
NULL inherits the saved analysis setting (FALSE for older objects without a setting). TRUE uses model-implied marginal endpoint SDs, with or without moderation. FALSE returns raw effects. |
Extraction never fits, imputes, or samples. Effect and contrast
intervals are percentile intervals from the stored joint draws, including
when bootstrap parameter tables were requested with bias correction.
For conditional standardization, moderator probes remain fixed in raw units.
Scales and coefficients vary jointly across draws. Invalid standardized draws
are excluded jointly and their original identities are recorded. For MI the
existing first-imputation reference and per-imputation centering are retained.
Endogenous products have an auxiliary moment model that retains the necessary
upstream residual covariances. MI moderated models jointly pool marginal
variances with coefficients, using a delta-method within-imputation covariance
and Rubin's rules; MC draws retain their covariance. Refit objects saved before
this correction. Finite MC draws or new imputations need not match after recoding.
The query interpretation records the plug-in outcome-difference SD.
Conditional result tables include extrapolated flags relative to observed
moderator values among used participants (imputed values excluded). Out-of-range
continuous probes signal wsmed_extrapolation_warning once per extraction;
this checks the marginal range, not joint covariate overlap or data density.
Categorical tables include n.observed, n.fitted.min, and n.fitted.max;
for MI the latter span the completed datasets and are not effective sample sizes.
The descriptive support metadata are retained in query$support.
Incompatible saved fits stop before extraction. If a fit is compatible but
its MI sampler is unversioned or outdated, rerun wsmed_infer() on that fit.
Stored primitive coefficients and full legacy tables remain inspectable.
A wsmed_results object with a full-precision table, joint effect draws, draw identities, query settings, and diagnostics.
The prepared analysis data used in the three wsMed manuscript examples, derived from the iWeek study deposited by Sagaribay (2025). Each row is one participant; T1 and T2 denote measurements before and after the study period. The examples use T2 minus T1 as the within-person contrast.
wsmed_exampleswsmed_examples
A data frame with 123 rows and 14 numeric columns:
Autonomous motivation scores at T1 and T2.
Subjective well-being scores at T1 and T2.
Daily social media use scores at T1 and T2.
Insomnia severity scores at T1 and T2.
DASS stress-subscale scores at T1 and T2, each calculated as the sum of the seven stress items.
Healthy eating scores at T1 and T2.
Age in years.
Body mass index, recalculated from weight in pounds and
height in inches using 703 * weight / height^2.
Score columns retain their prepared source values without rescaling or standardization. The original dataset contains 221 participants: 123 in the iWeek intervention group and 98 in the control group. This prepared dataset retains the 123 intervention-group participants. The wsMed examples illustrate within-person mediation using their paired T1/T2 measurements; they do not reproduce the original study's group comparison.
The manuscript authors retained the 14 analysis columns and recalculated BMI.
Height values outside the preparation rule of 48–84 inches, including
ambiguous units, were not converted by guesswork. BMI remains missing for
13 such records. No further participants were removed, no values were imputed,
and no additional cleaning is performed when creating this package dataset.
SPSS storage attributes are omitted; numerical values, row order, and missing
positions match the prepared wsMed_examples.sav replication file.
Across these 14 columns, 55 participants (44.7 percent) have at least one missing value, with 146 missing cells in total. Missing counts for paired T1/T2 columns are TSRQ: 1/22; WEMBS: 0/22; SMUF: 8/18; ISI: 0/19; DASSS: 0/23; HES: 0/20. Age is complete and BMI has 13 missing values. Counts for an individual analysis depend on the variables it selects.
In Examples 1 and 3, TSRQ, WEMBS, and SMUF are mediators; in Example 2, WEMBS and ISI precede TSRQ. DASSS is the outcome, HES is a within-subject covariate, and BMI is a between-subject covariate. Age is a covariate in Examples 1 and 2 and the moderator in Example 3.
The source data and this prepared derivative are distributed under CC BY 4.0, separately from the package code's GPL license. Attribution and modification information are also installed in ‘COPYRIGHTS’.
Sagaribay, R. (2025). iWeek: A Week-Long Social Media Abstinence Intervention and its Impact on Well-Being, Mental Health, Body Image, and Sleep in Latina College Students. Mendeley Data, version 1. doi:10.17632/fn9n95bsh5.1. License: https://creativecommons.org/licenses/by/4.0/.
example_data(), wsMed(), wsmed_fit()
data(wsmed_examples) dim(wsmed_examples) colSums(is.na(wsmed_examples)) sum(!complete.cases(wsmed_examples))data(wsmed_examples) dim(wsmed_examples) colSums(is.na(wsmed_examples)) sum(!complete.cases(wsmed_examples))
Fit a specified mediation model without simulation
wsmed_fit( model, data, missing = c("error", "listwise", "fiml", "mi"), mi = list(), fixed.x = FALSE, verbose = FALSE, standardized = FALSE )wsmed_fit( model, data, missing = c("error", "listwise", "fiml", "mi"), mi = list(), fixed.x = FALSE, verbose = FALSE, standardized = FALSE )
model |
A |
data |
A wide data frame with one row per participant. |
missing |
Missing-data strategy: error, listwise, fiml, or mi. |
mi |
MI controls: m, method, seed, or completed. Supply |
fixed.x |
Whether exogenous moments are fixed in the SEM. |
verbose |
Show progress messages. |
standardized |
Logical default for effect extraction, summaries and plots. Does not change model fitting; inference inherits this setting. |
This release preserves the existing per-imputation centering and
first-imputation reporting reference. It does not implement MI-bootstrap.
Factor outcome, mediator, and within-subject covariate columns are unsupported.
See wsmed_categorical for reference coding, numeric 0/1 predictors, and
restrictions on missing categorical predictors. mi$method specifies the
method for numeric variables; factors use logistic or multinomial regression.
Default imputation uses main effects and need not preserve substantive-model
interactions. For moderated models, consider model-compatible external
imputation (e.g., SMC-FCS) and pass its completed datasets. Supplied datasets
must preserve participant order, row names, observed values and factor levels,
and complete all analysis variables. Difference scores and products are
rebuilt separately in every dataset, then the same Rubin/MC engine is used.
Validation does not establish imputation-model compatibility. Save the external
imputer's settings, convergence diagnostics and software versions separately.
Internal MI with moderator interactions signals one
wsmed_mi_compatibility_warning per fit and records it in fit diagnostics.
Numeric 0/1 moderators remain continuous in this interface; a message explains
this choice. For categorical predictors in either interface, use unordered
factors with explicit levels; the first level is the reference group.
Type messages are retained as
diagnostics$input_notes and do not change estimates or random-number state.
Diagnostics include dataset-level convergence/admissibility, covariance checks,
case counts, warnings, and fitted category counts. Complete-case matrix rank
is descriptive, not an identification test for FIML. Counts below five receive
a descriptive small-category flag, not a universal validity cutoff.
Constant transformed variables are named in pre-fit errors. Non-converged
MI datasets stop pooling; known inadmissible fits cannot enter inference.
A wsmed_fit containing all fits and pooled estimates for MI.
Apply uncertainty quantification to an existing fit
wsmed_infer( object, method = c("mc", "bootstrap"), draws = NULL, seed = NULL, level = 0.95, interval = "perc", decomposition = "eigen", pd = TRUE, tol = 1e-06 )wsmed_infer( object, method = c("mc", "bootstrap"), draws = NULL, seed = NULL, level = 0.95, interval = "perc", decomposition = "eigen", pd = TRUE, tol = 1e-06 )
object |
A |
method |
mc or bootstrap. MI currently supports mc only. |
draws |
Number of draws; defaults to 20000 for mc and 2000 for bootstrap. |
seed |
Random seed, independent of the imputation seed. |
level |
Confidence level. |
interval |
Bootstrap interval type: perc, bc, or bca.simple. This controls the legacy parameter table stored in the inference backend. Effect extraction and confint methods always use percentile intervals. bca.simple uses zero acceleration, rather than a full BCa calculation. |
decomposition |
MI covariance factorization: eigen, chol, or svd. |
pd, tol
|
MI covariance checks; passed to the existing sampler. |
Inference never reimputes or changes the supplied fit. Bootstrap necessarily fits resampled datasets. No new statistical engine is introduced. Seeded calls restore the caller's random state; seed = NULL consumes the current random stream and advances it normally. Fits with endogenous products must record compatible model and MI pooling algorithm identifiers. Older unversioned moderated fits require refitting from the original data; package version alone cannot identify their algorithms.
A wsmed_inference storing draws and the original fit.
Inspect a modular workflow without recomputation
wsmed_inspect( object, component = c("model", "syntax", "data", "fits", "diagnostics", "provenance") )wsmed_inspect( object, component = c("model", "syntax", "data", "fits", "diagnostics", "provenance") )
object |
A wsmed_model, wsmed_fit, wsmed_inference, or wsMed object. |
component |
model, syntax, data, fits, diagnostics, or provenance. |
The requested specification, syntax, data, backend fits, or metadata.
Methods for modular wsMed objects
## S3 method for class 'wsMed' print( x, digits = 3, detail = c("effects", "full", "overview", "legacy"), type = "all", at = NULL, standardized = NULL, method = NULL, level = NULL, scale = NULL, ... ) ## S3 method for class 'wsmed_model' print(x, ...) ## S3 method for class 'wsmed_fit' print(x, digits = 3, ...) ## S3 method for class 'wsmed_inference' print(x, ...) ## S3 method for class 'wsmed_fit' summary(object, ...) ## S3 method for class 'summary_wsmed_fit' print(x, digits = 3, ...) ## S3 method for class 'wsmed_inference' summary( object, type = "all", at = NULL, scale = NULL, standardized = NULL, ... ) ## S3 method for class 'wsMed' summary( object, type = "all", at = NULL, scale = NULL, method = NULL, standardized = NULL, ... ) ## S3 method for class 'wsmed_fit' coef(object, ...) ## S3 method for class 'wsmed_fit' vcov(object, ...) ## S3 method for class 'wsmed_fit' nobs(object, ...) ## S3 method for class 'wsmed_inference' coef(object, ...) ## S3 method for class 'wsmed_inference' vcov(object, ...) ## S3 method for class 'wsmed_inference' nobs(object, ...) ## S3 method for class 'wsMed' coef(object, ...) ## S3 method for class 'wsMed' vcov(object, ...) ## S3 method for class 'wsMed' nobs(object, ...) ## S3 method for class 'wsmed_fit' confint(object, parm, level = NULL, ...) ## S3 method for class 'wsmed_inference' confint(object, parm, level = NULL, standardized = NULL, scale = NULL, ...) ## S3 method for class 'wsMed' confint( object, parm, level = NULL, method = NULL, standardized = NULL, scale = NULL, ... ) ## S3 method for class 'wsmed_results' print(x, digits = 3, ...) ## S3 method for class 'wsmed_results' summary(object, level = NULL, ...) ## S3 method for class 'wsmed_results' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S3 method for class 'wsmed_results' coef(object, ...) ## S3 method for class 'wsmed_results' vcov(object, ...) ## S3 method for class 'wsmed_results' confint(object, parm, level = NULL, ...) ## S3 method for class 'summary_wsmed' print(x, digits = 3, ...) ## S3 method for class 'summary_wsmed' summary(object, level = NULL, ...)## S3 method for class 'wsMed' print( x, digits = 3, detail = c("effects", "full", "overview", "legacy"), type = "all", at = NULL, standardized = NULL, method = NULL, level = NULL, scale = NULL, ... ) ## S3 method for class 'wsmed_model' print(x, ...) ## S3 method for class 'wsmed_fit' print(x, digits = 3, ...) ## S3 method for class 'wsmed_inference' print(x, ...) ## S3 method for class 'wsmed_fit' summary(object, ...) ## S3 method for class 'summary_wsmed_fit' print(x, digits = 3, ...) ## S3 method for class 'wsmed_inference' summary( object, type = "all", at = NULL, scale = NULL, standardized = NULL, ... ) ## S3 method for class 'wsMed' summary( object, type = "all", at = NULL, scale = NULL, method = NULL, standardized = NULL, ... ) ## S3 method for class 'wsmed_fit' coef(object, ...) ## S3 method for class 'wsmed_fit' vcov(object, ...) ## S3 method for class 'wsmed_fit' nobs(object, ...) ## S3 method for class 'wsmed_inference' coef(object, ...) ## S3 method for class 'wsmed_inference' vcov(object, ...) ## S3 method for class 'wsmed_inference' nobs(object, ...) ## S3 method for class 'wsMed' coef(object, ...) ## S3 method for class 'wsMed' vcov(object, ...) ## S3 method for class 'wsMed' nobs(object, ...) ## S3 method for class 'wsmed_fit' confint(object, parm, level = NULL, ...) ## S3 method for class 'wsmed_inference' confint(object, parm, level = NULL, standardized = NULL, scale = NULL, ...) ## S3 method for class 'wsMed' confint( object, parm, level = NULL, method = NULL, standardized = NULL, scale = NULL, ... ) ## S3 method for class 'wsmed_results' print(x, digits = 3, ...) ## S3 method for class 'wsmed_results' summary(object, level = NULL, ...) ## S3 method for class 'wsmed_results' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S3 method for class 'wsmed_results' coef(object, ...) ## S3 method for class 'wsmed_results' vcov(object, ...) ## S3 method for class 'wsmed_results' confint(object, parm, level = NULL, ...) ## S3 method for class 'summary_wsmed' print(x, digits = 3, ...) ## S3 method for class 'summary_wsmed' summary(object, level = NULL, ...)
x, object
|
A wsMed or modular workflow object. |
digits |
Number of displayed digits. Stored estimates are not rounded. |
detail |
effects (default) for core effects, full for effects and path coefficients, overview for fit status, or legacy for original stored tables. |
type, at, scale, method
|
Passed to |
standardized |
NULL inherits the saved analysis setting; TRUE or FALSE overrides it without fitting or sampling. Applies with or without moderation. |
level |
Confidence level. NULL uses the level saved in the selected inference or results object. |
... |
Additional arguments, passed to effect extraction by summary and confint methods. See wsmed_plots for plotting arguments. |
parm |
Names or positions of parameters/effects to include in intervals. |
row.names, optional
|
Standard data-frame conversion arguments. |
print methods return their input invisibly. summary returns a summary_wsmed (also a wsmed_results) for inference/one-call objects, or a summary_wsmed_fit for fits. Structured summaries contain effects and coefficients data frames, info, diagnostics and selected joint effect draws. as.data.frame, coef, confint, vcov and plot on the summary concern the selected effects; coefficients contains conditional path slopes (not all primitive parameters). Use type = 'parameters' for primitive parameters. Summary display uses printCoefmat; tables retain full precision. coef returns a named numeric vector. vcov returns the fit covariance (Rubin-pooled for MI), or the empirical covariance of stored draws for inference/results. confint recomputes percentile limits from stored draws without sampling. Its default level is the saved level, including when called on an inference or one-call object; use an explicit level to override it. On those two classes confint concerns native primitive parameters, matching coef and vcov regardless of the reporting preference (explicit scale overrides are accepted). Fit-only summaries also describe native parameters. Extract effects first to obtain indirect/conditional-effect intervals. nobs returns the sample size for each fitted dataset. as.data.frame returns a full-precision results table. plot returns a ggplot.
wsmed_reproducibility() for an exportable analysis manifest.
Specify a two-condition mediation model
wsmed_model( outcome, mediators, conditions = names(outcome), covariates = list(), structure = "parallel", paths = NULL, moderator = NULL )wsmed_model( outcome, mediators, conditions = names(outcome), covariates = list(), structure = "parallel", paths = NULL, moderator = NULL )
outcome |
Named pair of outcome columns, in condition order. |
mediators |
Named list of pairs of mediator columns. |
conditions |
Two condition names. Defaults to the outcome pair names. |
covariates |
List with |
structure |
One of parallel, serial, serial_parallel, parallel_serial, or custom. Mediator order matters for predefined serial structures. |
paths |
Directed edges using mediator role names and Y, for custom models. |
moderator |
NULL or a list with |
All moderator main effects are explicitly included in all difference
equations. Difference-slope and average-slope interactions are separate.
Categorical between-subject predictors must be unordered factors in the
staged workflow. Use the same explicit factor declaration with wsMed().
Set factor levels explicitly; the first level is the reference group.
A wsmed_model specification, without data or fitted estimates.
wsmed_categorical for supported variable roles and factor coding.
Plot stored effects without fitting, imputing, or drawing new samples.
The returned ggplot contains the full-precision plotted table in data.
## S3 method for class 'wsMed' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_inference' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_fit' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_results' plot( x, view = c("auto", "forest", "curve", "conditional"), terms = NULL, level = NULL, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, ... )## S3 method for class 'wsMed' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_inference' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_fit' plot( x, type = "indirect", terms = NULL, at = NULL, scale = NULL, method = NULL, level = NULL, view = c("auto", "forest", "curve", "conditional"), n = 51L, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, rug = FALSE, standardized = NULL, ... ) ## S3 method for class 'wsmed_results' plot( x, view = c("auto", "forest", "curve", "conditional"), terms = NULL, level = NULL, labels = NULL, title = NULL, x_label = NULL, y_label = NULL, ncol = NULL, base_size = 12, ... )
x |
A wsMed, wsmed_fit, wsmed_inference, or wsmed_results object. |
type |
Effect family passed to |
terms |
Effect identifiers to select, in display order. For a results object, use either effect identifiers or complete row identifiers. |
at |
Named list of raw moderator values or factor labels. |
scale, method
|
Passed to |
level |
Confidence level. NULL retains the stored level. For an extracted results object, intervals can be recalculated from its stored effect draws. |
view |
One of auto, forest, curve, or conditional. Auto uses a curve for a continuous moderator, separate category points for a categorical moderator, and a forest plot for unmoderated effects, single probes, and contrasts. |
n |
Number of equally spaced probes for an automatic continuous curve (default 51). The range is the finite moderator range among cases used by the first fitted dataset. In MI this is the first completed dataset. |
labels |
Named character vector mapping effect identifiers to labels. Labels must distinguish effects. Defaults use mediator role names. |
title, x_label, y_label
|
Optional title and axis labels. |
ncol |
Number of facet columns, or NULL. |
base_size |
Positive base font size. |
rug |
Add observed raw moderator values along a continuous curve's horizontal axis. Available for fitted/inference/one-call objects only. Uses fitted cases with an observed moderator; imputed values are excluded. |
standardized |
NULL inherits the analysis setting; TRUE or FALSE overrides it for this plot. Available on fit, inference and one-call objects. |
... |
Additional arguments are rejected to catch misspellings. |
Curves connect finite probes; bands are pointwise percentile
intervals, not simultaneous bands or Johnson–Neyman regions. Supplied probes
outside the observed fitted-case range are identified in the caption and
plotted data (extrapolated). Group counts appear in categorical captions;
for MI these are ranges across completed datasets, not effective sample sizes.
Plot metadata retain support, including the observed range or group counts.
remain in raw units. A continuous conditional point plot requires explicit
at values. Forest plots without at use the usual reference value.
Category and effect selections retain their supplied order. A fitted object
without inference produces point estimates only, with no confidence band.
Extracted results contain only their selected effects and probes: plotting
them never invents a new grid. Use wsmed_effects() again to change the scale,
method, or probes. wsmed_contrasts() constructs differences from joint draws.
Marginal standardization uses the same draw-specific scales as effect
extraction; it does not standardize a plotted table after computing intervals.
The older plot_effects(), plot_conditional_effects(), plot_contrasts(),
and plot_moderation_curve() calls remain available. For wsMed objects those
helpers preserve the stored legacy tables, including requested bootstrap
interval types. The plot methods here use the percentile convention of
wsmed_effects(). Plots explicitly identify their interval source.
A ggplot. Its wsmed_plot attribute records the method, scale,
confidence level, interval convention, view, and automatic-grid range.
wsmed_effects(), wsmed_contrasts(), wsmed_methods
data(example_data) model <- wsmed_model(c(before = "D1", after = "D2"), list(A = c(before = "A1", after = "A2")), moderator = list(variable = "D3", interactions = "A -> Y")) fit <- wsmed_fit(model, example_data) plot(fit, n = 21, title = "Conditional point estimates")data(example_data) model <- wsmed_model(c(before = "D1", after = "D2"), list(A = c(before = "A1", after = "A2")), moderator = list(variable = "D3", interactions = "A -> Y")) fit <- wsmed_fit(model, example_data) plot(fit, n = 21, title = "Conditional point estimates")
Export the settings and provenance of an analysis
wsmed_reproducibility(object, file = NULL)wsmed_reproducibility(object, file = NULL)
object |
A wsmed_model, wsmed_fit, wsmed_inference, wsmed_results, or current wsMed object. A one-call object exports all stored inference methods. |
file |
Optional new .rds file for the report. Existing files are not overwritten. |
This report contains no participant-level data or simulation draws. It is an analysis manifest, not a replacement for the data, analysis script, or a dependency lockfile. It never fits, imputes, samples, or updates results. Recorded fitting versions are separated from the environment used to export. Metadata absent from an older saved object remain absent, not reconstructed from currently installed package versions. Reports for extracted results include the query and contrast definition as well as the upstream settings.
A plain list of model specification, settings, reference coding, diagnostics, and recorded software versions; invisibly when written to file.
data(example_data) m <- wsmed_model(c(before = "D1", after = "D2"), list(A = c(before = "A1", after = "A2"))) f <- wsmed_fit(m, example_data) report <- wsmed_reproducibility(f) report$analysis$missingdata(example_data) m <- wsmed_model(c(before = "D1", after = "D2"), list(A = c(before = "A1", after = "A2"))) f <- wsmed_fit(m, example_data) report <- wsmed_reproducibility(f) report$analysis$missing