Investigation: Mediation and moderation

Investigation: Mediation and moderation#

An interaction describes how a conditional association varies. Causal moderation and mediation require additional design and identification assumptions. A disappearing direct-effect p-value is neither necessary nor sufficient to establish causal mediation.

Question. Generate a system with a known indirect effect, then add an unmeasured common cause of mediator and outcome. Compare fitted products with the known intervention effect.

Before running: write the result you expect and what would challenge it. Data are simulated unless explicitly identified otherwise.

# Open this notebook from book/notebooks (or book/exercises).
course_path <- if (file.exists("../R/course.R")) "../R/course.R" else "book/R/course.R"
stopifnot(file.exists(course_path))
source(course_path)
set.seed(432)

Known mechanism and a hidden confounder#

We simulate X → M → Y and X → Y. In the second scenario an unmeasured U affects both M and Y. Randomizing X does not remove mediator–outcome confounding.

simulate_mediation <- function(n=800,confounding=0) {
  x <- rnorm(n); u <- rnorm(n)
  m <- .7*x+confounding*u+rnorm(n)
  y <- .3*x+.8*m+confounding*u+rnorm(n)
  data.frame(x=x,m=m,y=y)
}
indirect <- function(d) unname(coef(lm(m~x,d))[2]*coef(lm(y~x+m,d))[3])
clean <- simulate_mediation(confounding=0)
confounded <- simulate_mediation(confounding=1)
c(true_indirect=.7*.8,unconfounded_estimate=indirect(clean),confounded_estimate=indirect(confounded))
B <- 500
boot <- replicate(B,indirect(clean[sample.int(nrow(clean),replace=TRUE),]))
quantile(boot,c(.025,.975))
true_indirect
0.56
unconfounded_estimate
0.596574403359939
confounded_estimate
0.915773313226994
2.5%
0.518892106564011
97.5%
0.682008511012612

This product estimates an indirect association. A causal interpretation also needs appropriate consistency, positivity, temporal ordering, and confounding assumptions, including assumptions about mediator–outcome confounders affected by exposure. A bootstrap interval does not supply identification. In mediation::mediate(), boot=FALSE uses quasi-Bayesian simulation; sims is not an unused label. A proportion mediated divides the indirect effect by the total effect and can be unstable near a zero total effect.

d <- data.frame(x=rnorm(200),m=rnorm(200))
d$y <- 1+d$x+.5*d$m+.8*d$x*d$m+rnorm(200)
fit <- lm(y~x*m,d)
new <- expand.grid(x=seq(-2,2,length.out=50),m=c(-1,0,1))
new$prediction <- predict(fit,new)
matplot(seq(-2,2,length.out=50),matrix(new$prediction,ncol=3),type="l",lty=1:3,col=c("black","blue","red"),xlab="x",ylab="Predicted y")
legend("topleft",c("m=-1","m=0","m=1"),lty=1:3,col=c("black","blue","red"))

Moderation is modeled with the continuous interaction. Correlated predictors can affect precision but do not automatically invalidate this regression. A significant interaction is not, on its own, an identified causal effect modification.

Interpret and verify#

Draw the causal graph, list assumptions, and compare estimates under a confounded and unconfounded simulator. Plot continuous interactions without median splitting.

Failure to consider: Observed associations can mimic mediation. Correlation between predictors is not itself a violation of linear regression; causal identification is a different problem.

Report the target, the numerical result with its units, the relevant uncertainty, and one limitation. Distinguish what is established by the simulation from what would require real data.

AI audit: critique the saved faulty claim in the companion exercise before using any live assistant. If you use AI, record the relevant suggestion, your independent check, and the final decision.

Apply the earlier distinction between prediction and explanation; power simulations must reproduce the actual planned analysis.

sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS 15.7.7

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] C.UTF-8/C.UTF-8/C.UTF-8/C/C.UTF-8/C.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] fansi_1.0.3         crayon_1.5.1        digest_0.6.29      
 [4] utf8_1.2.2          IRdisplay_1.1       repr_1.1.4         
 [7] lifecycle_1.0.1     jsonlite_1.8.0      evaluate_0.15      
[10] pillar_1.8.0        rlang_1.0.6         cli_3.3.0          
[13] uuid_1.1-0          vctrs_0.4.1         IRkernel_1.3.0.9000
[16] tools_4.2.1         glue_1.6.2          fastmap_1.1.0      
[19] compiler_4.2.1      base64enc_0.1-3     pbdZMQ_0.3-7       
[22] htmltools_0.5.3    

Attribution#

Notebook authored by Patience Stevens and edited by Amy Sentis.

Revised investigation: 2026 course revision. Original authorship is retained; examples and explanatory text have been updated.