perform a mediation in r

Performing a mediation analysis in R involves several steps. Here is a brief overview of the process:

  1. Load necessary libraries: mediation, car, and ggplot2.
main.r
library(mediation)
library(car)
library(ggplot2)
49 chars
4 lines
  1. Prepare data: We need three variables - the predictor, mediator, and outcome variables. We'll call them X, M, and Y, respectively.

  2. Check for assumptions: Before we run the analysis, we need to check that our data meets certain assumptions, such as normality, linearity, and homoscedasticity. We can do this with diagnostic plots and tests.

  3. Run regression models: Run regression models to estimate the direct effect of X on Y (path c), the effect of X on M (path a), and the effect of M on Y controlling for X (path b).

main.r
model_a <- lm(M ~ X, data = mydata)
model_c <- lm(Y ~ X, data = mydata)
model_b <- lm(Y ~ M + X, data = mydata)
112 chars
4 lines
  1. Run mediation analysis: Use the mediate() function to estimate the indirect effect of X on Y via M and the total effect of X on Y.
main.r
med_model <- mediate(model_a, model_b, model_c, treat = "X", mediator = "M", boot = TRUE, sims = 1000)
summary(med_model)
122 chars
3 lines
  1. Interpret results: The output will show the estimated direct effect of X on Y (path c), the effect of X on M (path a), the effect of M on Y controlling for X (path b), the indirect effect of X on Y via M, and the total effect of X on Y (sum of direct and indirect effects). We can also examine the bootstrapped confidence intervals to assess the significance of the indirect effect.

  2. Visualize results: We can create a plot to visualize the mediation model using plot(med_model) and plot(med_model, type = "indirect").

This is a basic overview of how to perform a mediation analysis in R. There are many variations and extensions of mediation analysis, but this should give you a good start.

gistlibby LogSnag