Learn R Programming

wsMed

The wsMed function is designed for two condition within-subject mediation analysis, incorporating SEM models through the lavaan package and Monte Carlo simulation methods. This document provides a detailed description of the function's parameters, workflow, and usage, along with an example demonstration.

Installation

You can install the development version of wsMed from GitHub with:

# install.packages("pak")
pak::pak("Yangzhen1999/wsMed")

Alternatively, if you prefer using devtools, you can install wsMed as follows:

# install.packages("devtools")
devtools::install_github("Yangzhen1999/wsMed")

Example

This is a basic example which shows you how to solve a common problem:

library(wsMed)

# Load example data
data(example_data)
set.seed(123)
example_dataN <- mice::ampute(
data = example_data,
prop = 0.1,
)$amp

# Perform within-subject mediation analysis (Parallel mediation model)
result <- wsMed(
data = example_dataN,   #dataset
M_C1 = c("A1","B1"),    # A1/B1 is A/B mediator variable in condition 1
M_C2 = c("A2","B2"),    # A2/B2 is A/B mediator variable in condition 2
Y_C1 = "C1",            # C1 is outcome variable in condition 1
Y_C2 = "C2",            # C2 is outcome variable in condition 2
form = "P",             # Parallel mediation
C_C1 = "D1",            # within-subject covariate (e.g., measured under D1)
C_C2 = "D2",            # within-subject covariate (e.g., measured under C2)
C = "D3",               # between-subject covariates
Na = "MI",              # Use multiple imputation for missing data
standardized = TRUE,    # Request standardized path coefficients and effects
)

# Print summary results
print(result)

Main Function Overview

The wsMed() function automates the full workflow for two-condition within-subject mediation analysis. Its main steps are:

  1. Validate inputs – check dataset structure, mediation model type (form), and missing-data settings.

  2. Prepare data – compute difference scores (Mdiff, Ydiff) and centered averages (Mavg) from the two-condition variables.

  3. Build the model – generate SEM syntax according to the chosen structure:

    • "P": Parallel mediation
  1. Fit the model – estimate parameters while handling missing data:

    • "DE": listwise deletion
    • "FIML": full-information ML
    • "MI": multiple imputation
  2. Compute inference – provide confidence intervals using:

    • Bootstrap (ci_method = "bootstrap")
    • Monte Carlo (ci_method = "mc")
  3. Optional: Standardization – if standardized = TRUE, return standardized effects with CIs.

  4. Optional: Covariates – automatically center and include:

    • Between-subject covariates (C): mean-centered and added to all regressions.
    • Within-subject covariates (C_C1, C_C2): difference scores and centered averages are computed and included.

Copy Link

Version

Install

install.packages('wsMed')

Version

1.0.2

License

GPL (>= 3)

Maintainer

Wendie Yang

Last Published

December 11th, 2025

Functions in wsMed (1.0.2)

assert_scalar_int

Assert a scalar (whole-number) integer with optional bounds
ThetaHatStarWrapper

Monte Carlo Sampling for Parameter Estimates
TotalAdjwrapper

Adjusted Total Sampling Covariance Matrix
analyze_mm_continuous

Conditional Indirect Effects with a Continuous Moderator
evaluate_definitions_unstd_v2

Evaluate Unstandardized Monte Carlo Definitions
ThetaHatWrapper

Compute Updated Parameter Estimates for SEM Models
apply_standardization

Apply Standardization to Parameter Definitions
.make_moderation

Create moderation output for wsMed
build_path_std_map

Build Standardization Maps PATH
.fit_and_mc

Fit SEM and run Monte-Carlo draws
fix_ci_names

Fix legacy CI column names in a data.frame
build_definitions

Build Unstandardized Parameter Definitions
.v

Verbose message wrapper (internal)
evaluate_definitions_v3

Evaluate Standardized Monte Carlo Expressions
fix_pct_names

Fix % characters mangled by make.names()
dbg

Debug printer with indentation (internal)
add_sig

Append significance stars based on CI
TransformMidsWithPrepareData

Apply PrepareData to Imputed Datasets and Return New MIDS Object
build_std_map

Build Standardization Maps
.make_ci_names

Make CI column names like "2.5%CI.Lo / 97.5%CI.Up"
bootstrap_sd_list

Bootstrap Standard Deviations for Standardization
get_indirect_paths

Parse All Possible Indirect Paths from Column Names
calc_basic_contrasts

Basic Contrasts for Indirect Effects and Pre/Post Path Coefficients
get_sd_target_variables

Extract Target Variables for Standardization
plot_moderation_curve

Plot moderation curves with Johnson-Neyman highlights
make_contrasts

make_contrasts
get_safe_ncpus

Get safe number of CPUs for parallel processing
generate_mc_samples

Generate Monte Carlo Samples
mc_summary_pct

Compute Monte Carlo Estimates, Standard Errors, and CIs (with Percent Labels)
get_all_variables_from_path_map

Extract All Variables Needed for Standardization
summarize_mc_ci

Summarize Monte Carlo Simulation Results
.clean_ci_names

Clean all CI column names into the standard form
extract_all_parameters

Extract All Parameters and Definitions
example_data

Example Data for within subject mediation
validate_wsMed_inputs

Validate user inputs for wsMed()
print.wsMed

Print Method for wsMed Objects
null_coalesce

Null-coalescing operator
wsMed

Within-Subject Mediation Analysis (Two-Condition)
printGM

Print Formatted SEM Model Syntax
resolve_all_dependencies

Resolve Dependencies of Defined Parameters
sort_parameters

Sort Parameters for Printing in SEM Output
run_mc_mediation

Run Monte Carlo-Based Mediation Inference
GenerateModelP

Generate Parallel Mediation Model
GenerateModelCP

Generate Combined Parallel and Chained Mediation Model
ImputeData

Impute Missing Data Using Multiple Imputation
GenerateModelPC

Generate Parallel and Chained Mediation Model
GenerateModelCN

Generate Chained Mediation Model
MCStd2

Monte Carlo Summary for Standardized Estimates
Lav2RAM2

Convert Lavaan Model to RAM Matrices
MCMI2

Monte Carlo Confidence Intervals for Multiple Imputation SEM Models
PrepareData

Prepare Data for Two-Condition Within-Subject Mediation (WsMed)
ARIVwrapper

Average Relative Increase in Variance
MICombineWrapper

Wrapper for Internal Multiple Imputation Combining Function
RAM2Lav2

Convert Standardized RAM Back to Lavaan Matrices
MCDefWrapper

Process Monte Carlo Samples for Defined Parameters in SEM
PrepareMissingData

Prepare Data with Missing Values for Mediation Analysis
TestPositiveDefinitewrapper

Test for a Positive Definite Matrix
StdRAM2

Standardize RAM Matrices
RandomGaussianSVDwrapper

Generate Random Variates from the Gaussian Distribution (Singular Value Decomposition)
StdLav2

Standardize Parameter Estimates in a Lavaan Model
RunMCMIAnalysis

Monte Carlo SEM with Multiple Imputation (WsMed Workflow)