1 Required libraries and source files

library(mediation)
library(dplyr)
library(ggplot2)
library(gt)
library(afcommon)

2 Creating Example Dataset

We’ll create a simulated dataset to demonstrate the mediation analysis functions:

set.seed(123)
n <- 1000

# Create variables with known relationships
treatment <- rbinom(n, 1, 0.5)
mediator <- 0.5 * treatment + rnorm(n, 0, 1)
outcome <- 0.3 * treatment + 0.4 * mediator + rnorm(n, 0, 1)

# Combine into dataframe
df <- data.frame(
  treatment = treatment,
  mediator = mediator,
  outcome = outcome
)

3 Running Mediation Analysis

Now we’ll perform the mediation analysis:

# Run mediation analysis
med_results <- af_mediation_analysis(
  df = df,
  outcome_var_name = "outcome",
  mediator_var_name = "mediator",
  treatment_var_name = "treatment"
)

# Print interpretation
result_line <- af_interpret_mediate_results(
  med_results,
  outcome_var_name = "outcome",
  mediator_var_name = "mediator",
  treatment_var_name = "treatment"
)

The results of the causal mediation analysis shows 52.2 % of treatment total effect on outcome is mediated through mediator .

4 Examining Detailed Results

Let’s look at the complete mediation analysis results:

  • ACME (Average Causal Mediation Effect) - The indirect effect of the treatment that goes through the mediator variable.
  • ADE (Average Direct Effect) - The direct effect of the treatment on the outcome that doesn’t go through the mediator.
  • ACME + ADE - Total Effect of the treatment on the outcome.
# summary(med_results)
af_create_mediation_table(med_results)
Causal Mediation Analysis Results
Effect1 Estimate 95% CI Lower 95% CI Upper p-value
ACME 0.2316 0.1717 0.3018 0.00
ADE 0.2116 0.0896 0.3359 0.00
Total Effect 0.4432 0.3136 0.5830 0.00
Prop. Mediated 0.5225 0.3851 0.7416 0.00
1 ACME = Average Causal Mediation Effect; ADE = Average Direct Effect

Visualize the mediation effects:

Note: This plot shows:

  • ACME (Average Causal Mediation Effect): The indirect effect through the mediator
  • ADE (Average Direct Effect): The direct effect of treatment on outcome
  • Total Effect: Combined effect (ACME + ADE)

The dots show point estimates, lines show 95% confidence intervals

# plot(med_results)
af_plot_mediation_effects(med_results)

Visualize mediation model coefficients:

af_plot_mediation_coefficients(med_results)