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
)
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 .
Let’s look at the complete mediation analysis 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:
The dots show point estimates, lines show 95% confidence intervals
Visualize mediation model coefficients: