Mediation and Moderation in Python and R Without SPSS PROCESS

Transitioning from the proprietary SPSS PROCESS macro to open-source R and Python eliminates licensing barriers, automates repetitive modeling steps, and provides reproducible bootstrap confidence intervals for mediation and moderation analyses.

HumanPen Team

· 11 min read

Replicating SPSS PROCESS in Python and R for Mediation and Moderation

You can replicate SPSS PROCESS mediation and moderation models in R and Python without proprietary plugins by using `lavaan` or `pingouin`. In R, `lavaan` estimates path equations and non-parametric bootstrap confidence intervals for indirect effects (`a × b`) using `se = 'bootstrap'`. In Python, `pingouin.mediation_analysis` calculates bootstrap intervals directly, while `statsmodels` handles interaction probing, simple slopes, and Johnson-Neyman intervals for reproducible, scriptable reporting.

Core takeaway: The proprietary SPSS PROCESS macro relies on closed point-and-click execution that hampers automated workflows and pipeline versioning. Migrating to open-source ecosystems like R `lavaan` or Python `pingouin` preserves exact mathematical equivalence while embedding data cleaning, model estimation, and publication-ready path tables into a single script.

Quantitative researchers across management, psychology, and public health frequently encounter obstacles when institutional SPSS licenses expire or when journals request fully reproducible code pipelines. For over a decade, Andrew Hayes's PROCESS macro served as the default tool for testing mediation, moderation, and conditional process models. However, relying on menu-driven SPSS dialogs introduces human transcription errors, obscures batch sensitivity analyses across alternative covariates, and prevents automated re-execution when upstream datasets update. By expressing path models directly in open-source R and Python scripts, researchers secure verifiable execution, eliminate software license bottlenecks, and maintain compliance with open-science replication standards.

Why Bootstrap Confidence Intervals Replaced the Sobel Test for Indirect Effects

In classical mediation analysis, Baron and Kenny's causal steps and the Sobel z-test evaluated whether the indirect pathway from predictor `X` through mediator `M` to outcome `Y` reached statistical significance. The Sobel test assumes that the product of two regression coefficients, `a` (the effect of `X` on `M`) and `b` (the effect of `M` on `Y` controlling for `X`), follows a standard normal distribution. However, as demonstrated by Preacher and Hayes (2008) in their seminal work on asymptotic and resampling strategies, even when the individual regression coefficients `a` and `b` are normally distributed, their product `a × b` exhibits a distinctly skewed, leptokurtic distribution in finite samples. Forcing a symmetric Gaussian bell curve onto this asymmetric distribution depresses statistical power and inflates Type I error rates when sample sizes are modest.

Inferential ApproachUnderlying Distribution AssumptionSampling Asymmetry HandlingType I Error & Statistical PowerRecommended Implementation
Sobel Normal-Theory TestAssumes product `a × b` follows asymptotic standard normal distributionSymmetrical intervals centered on point estimate, ignoring positive or negative skewnessUnderpowered in small-to-moderate samples; elevated Type I error under non-normalityDeprecated in modern empirical literature; retained only for historical comparison
Non-Parametric Percentile BootstrapEmpirical resampling distribution constructed directly from observed dataSorts `R` resampled indirect effects; empirical 2.5th and 97.5th percentiles form boundsRobust against non-normal products; maintains nominal Type I error without distributional assumptions`lavaan` in R (`se = "bootstrap", bootstrap = 5000` with `parameterEstimates(..., boot.ci.type = "perc")`) or `pingouin.mediation_analysis(n_boot=5000)` in Python
Bias-Corrected (BCa) BootstrapResampling distribution adjusted for median bias and skewness accelerationAdjusts empirical percentile cutoffs according to proportion of resamples below point estimateMaximizes statistical power in smaller samples; can occasionally exhibit slight liberal bias`lavaan` with `parameterEstimates(..., boot.ci.type = "bca.simple")` or specialized R packages

Modern journal editors and methodological standards universally require reporting non-parametric bootstrap confidence intervals rather than relying on normal-theory p-values. In practice, researchers generate between 1,000 and 10,000 resamples—with 5,000 resamples (`R = 5000`) representing the standard scholarly threshold—to construct 95% confidence intervals. Mediation is statistically supported when the lower limit confidence interval (`LLCI`) and upper limit confidence interval (`ULCI`) do not straddle zero. If a 95% bootstrap confidence interval spans `[0.032, 0.145]`, the indirect effect is considered statistically significant at `p < 0.05`, providing robust evidence of mediation without relying on unrealistic distributional assumptions.

Mapping Hayes PROCESS Models to R lavaan and Python Pingouin Syntax

Migrating from SPSS PROCESS to scriptable environments requires translating numerical model templates into explicit regression formulas and structural equation paths. In SPSS, selecting `Model 4` runs a simple mediation model, `Model 1` specifies a simple moderation model, and `Model 7` or `Model 14` estimates moderated mediation with first-stage or second-stage conditional indirect effects. In R and Python, these models do not require opaque black-box macros; they are expressed transparently through simultaneous linear equations or structural equation modeling (`SEM`) syntax.

PROCESS Model IndexConceptual ArchitectureR `lavaan` / Script SpecificationPython `pingouin` / `statsmodels` ImplementationKey Output Parameter or Contrast
Model 4 (Simple Mediation)Predictor `X` affects `Y` directly and indirectly through single mediator `M``m ~ ax; y ~ bm + c_primex; ab := ab; total := c_prime + ab` fit via `sem()` with `se = 'bootstrap'``pingouin.mediation_analysis(data=df, x='X', m='M', y='Y', n_boot=5000, seed=42)`Indirect effect `ab`, direct effect `c_prime`, and total effect `total`
Model 1 (Simple Moderation)Effect of predictor `X` on outcome `Y` is conditioned by moderator `W``lm(y ~ x_c * w_c, data = df)` with interaction term `x_c:w_c``smf.ols('Y ~ X_c * W_c', data=df).fit()` using centered variables `X_c` and `W_c`Interaction coefficient `b3`, simple slopes at `±1 SD`, and Johnson-Neyman region
Model 7 (Moderated Mediation)Moderator `W` conditions indirect path `a` from `X` to `M` (first-stage moderation)`m ~ a1x + a2w + a3x:w; y ~ bm + c_primex; ind_low := (a1 + a3(mean_w - sd_w))b; ind_high := (a1 + a3(mean_w + sd_w))*b`Two chained `statsmodels` OLS regressions combined with custom percentile bootstrap resamplerIndex of moderated mediation `a3 × b` and conditional indirect effects across `W` levels
Model 14 (Moderated Mediation)Moderator `V` conditions indirect path `b` from `M` to `Y` (second-stage moderation)`m ~ ax; y ~ b1m + b2v + b3m:v + c_primex; ind_mod := a (b1 + b3 * v_level)` in `lavaan` syntaxChained OLS regressions modeling mediator and outcome with interaction term `M × V`Second-stage index of moderated mediation `a × b3` and conditional indirect effects
  • Define Path Coefficients Explicitly: In R `lavaan`, label path coefficients directly in regression formulas using the multiplication operator (such as `ax` and `bm`), allowing the syntax to define custom indirect parameters via `:=` (for instance, `ab := a*b`).
  • Set Fixed Random Seeds for Exact Replication: Specify an explicit pseudo-random seed (such as `set.seed(42)` in R or `seed=42` in Python) before initiating bootstrap resampling, ensuring that downstream colleagues generate identical confidence bounds.
  • Incorporate Control Covariates on All Dependent Paths: Add control variables to both the mediator model (`m ~ x + c1 + c2`) and the outcome model (`y ~ x + m + c1 + c2`), mirroring the exact covariate adjustment logic implemented in SPSS PROCESS.
  • Extract Both Standardized and Unstandardized Metrics: Retrieve unstandardized path estimates for direct hypothesis tests and standardized estimates (`std.all` in `lavaan` or `pingouin` effect sizes) for cross-study comparison and meta-analytic reporting.

Handling multiple covariates simultaneously is essential for rigorous empirical modeling. In SPSS PROCESS, users enter covariates into a dedicated dialog box, which automatically adjusts both the mediator and dependent equations. When constructing R `lavaan` scripts or Python regression pipelines, analysts must explicitly specify covariate paths across each sub-equation. Omitting covariates from the mediator equation while including them in the outcome equation alters the causal interpretation and leads to parameter discrepancies between SPSS output and scriptable alternatives.

Mean-Centering Predictors, Simple Slopes Probing, and Johnson-Neyman Regions

Estimating moderation models (equivalent to PROCESS Model 1) requires careful parameterization of the interaction term `X × W`. Multiplying raw predictor scores frequently induces substantial multicollinearity between the product term and its constituent linear terms, causing standard errors to inflate and complicating coefficient interpretation. When raw variables are used, the lower-order coefficient for `X` represents the effect of the predictor only when the moderator `W` equals zero—a value that may be mathematically impossible or substantively meaningless in Likert survey scales. By mean-centering both `X` and `W` prior to computing their product (`X_c = X - Mean(X)` and `W_c = W - Mean(W)`), the main effect of `X_c` reflects the regression slope at the sample mean of the moderator, providing an intuitive, interpretable baseline.

Core takeaway: Probing interaction effects at arbitrary moderator cuts (`±1 SD` or 16th, 50th, and 84th percentiles) can miss critical inflection points. Combining simple slopes pick-a-point testing with the Johnson-Neyman technique identifies the precise continuous range of the moderator where the focal predictor exerts a statistically significant effect.

To interpret significant moderation interactions, researchers traditionally conduct simple slopes analysis (often termed pick-a-point probing), evaluating the regression of `Y` on `X` at three characteristic levels of `W`: one standard deviation below the mean (`Mean - 1 SD`), at the mean (`Mean`), and one standard deviation above the mean (`Mean + 1 SD`). However, because choosing `±1 SD` is an arbitrary convention, methodologists strongly advocate supplementing simple slopes with the Johnson-Neyman technique. The Johnson-Neyman approach solves algebraically for the exact values of the continuous moderator where the conditional effect of `X` transitions across the threshold of statistical significance (`p = 0.05`). In Python, this is executed via `statsmodels` marginal effect functions or `probing` routines, while in R, packages such as `interactions` or `rockchalk` generate conditional slope plots with shaded 95% confidence bands, showing reviewers exactly where the moderation effect activates.

Running Reproducible Mediation and Moderation Workflows in HumanPen Start Project

Executing advanced conditional process modeling, parameter bootstrapping, and publication-ready table generation requires structured execution pipelines that bridge raw data and finished manuscript drafts. Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download. By automating script execution and table formatting within an auditable environment, research teams avoid the pitfalls of manual copy-pasting and proprietary software dependencies.

Platform capabilities and boundaries: HumanPen Start Project supports Excel, CSV, Word, PDF, and zip archives up to 2 GB per project, executing statistical and data analysis in an isolated sandbox using Python or R (SPSS and Stata analyses are performed via Python or R scripts). Commercial databases such as Wind or CNKI must be exported by the user beforehand, GPU training is not supported, and projects are billed in real time with a 6-month retention window and immediate deletion on demand.

This workflow is demonstrated across the live example projects hosted on HumanPen Start Project, where complex secondary analyses—such as clinical trial subgroup evaluations or observational survey regressions—are transformed into reproducible deliverables. In an empirical mediation project, the platform ingests raw survey CSV files, verifies variable types and missingness patterns, executes 5,000-resample bootstrap iterations in `lavaan` or Python, and compiles standardized APA path tables, conditional slope plots, and complete replication scripts into an integrated deliverable package. Authors preparing journal revisions can systematically verify empirical estimates using our methods and results revision checklist to ensure every reported path coefficient matches underlying computational logs.

For graduate researchers preparing master's dissertations or research teams submitting to peer-reviewed journals, deliverables generated by Start Project are designed strictly as reproducible learning scaffolds and methodological reference drafts. Authors maintain complete professional responsibility for inspecting the underlying Python or R code, verifying the theoretical soundness of specified mediation paths, and ensuring transparent academic reporting. Before submitting final empirical manuscripts, researchers should audit their complete submission package against our final manuscript pre-submission checklist and disclose analytical software tools in accordance with their institutional and journal policies.

Frequently Asked Questions About Scriptable Mediation and Moderation

Do R lavaan and Python pingouin produce results identical to the SPSS PROCESS macro?

Yes, when given identical data, missing-value treatments, and random seeds, R and Python yield point estimates identical to SPSS PROCESS. Minor numerical differences in bootstrap confidence bounds (typically in the third or fourth decimal place) occur solely because bootstrap sampling involves stochastic pseudo-random generation. Setting a fixed random seed (`set.seed()` in R or `seed` in Python) ensures that resampled confidence intervals replicate deterministically across re-runs.

How many bootstrap resamples should I specify for reporting indirect effects in academic papers?

Methodological standards and peer-reviewed journals recommend a minimum of 5,000 bootstrap resamples (`R = 5000`) for estimating indirect effect confidence intervals. While 1,000 resamples may suffice during exploratory model building, 5,000 iterations ensure that the empirical tail percentiles (such as the 2.5th and 97.5th cutoffs for a 95% confidence interval) remain stable and free from random resampling fluctuation.

How do I test moderated mediation (PROCESS Model 7 or Model 14) in R without SPSS?

In R, moderated mediation can be tested using structural equation modeling in `lavaan` or through chained linear regressions. In `lavaan`, you define the conditional indirect effect at specific levels of the moderator using the `:=` operator (for example, defining `ind_low := (a1 + a3 w_low) b` and `ind_high := (a1 + a3 w_high) b`). Alternatively, you can calculate the Index of Moderated Mediation directly as the product of the interaction path and the subsequent direct path (`a3 × b`), using bootstrap resampling to evaluate its 95% confidence interval.

Can I run mediation analysis if my mediator or dependent variable is binary?

Yes. When the mediator or outcome variable is binary or categorical, standard linear regression is replaced with logistic regression or probit link functions. In R, `lavaan` supports categorical outcomes using the `ordered = TRUE` parameter and the diagonally weighted least squares (`DWLS` or `WLSMV`) estimator. In Python, generalized linear models (`GLM`) in `statsmodels` or causal mediation packages handle binary outcome transformations while preserving bootstrap indirect effect calculations.

Sources and Methodological References

The statistical modeling principles, resampling frameworks, and open-source computational libraries referenced throughout this guide are based on peer-reviewed literature and official software documentation:

KEEP READING