HSCI 410 · Lesson 8

Mediation, Moderation and Path Analysis

Exploratory Data Analysis For Epidemiology

Learning objectives for this lesson:

  1. Classify a third variable in a causal diagram (DAG) as a confounder, a mediator or a collider, say what the analysis does with each, and explain why effect modification is a separate question that a DAG does not show as an arrow.
  2. Explain the total, direct and indirect effects and how they add up in a linear model, and state the conditions for reading an indirect effect causally, including temporal order and no unmeasured mediator-outcome confounding, which randomizing the exposure does not secure.
  3. Interpret a regression model with an interaction term: the interaction coefficient, the slope of the exposure in each group or at chosen values of the moderator, the main effects and the effect of centring, and the scale (additive or multiplicative) of the interaction.
  4. Interpret the paths of a mediation analysis (a, b, c and c′), the indirect effect with its bootstrap confidence interval and the proportion mediated, and explain why the Baron and Kenny steps and the labels “full” and “partial” mediation are no longer recommended.
  5. Interpret a sensitivity analysis for unmeasured mediator-outcome confounding, and judge whether an indirect association is robust or fragile.
  6. Read a path diagram and the results of a path model: judge its fit with the chi-square test and the fit indices, compare nested models, interpret standardized paths and R-squared values, and explain what a structural equation model with latent variables adds and what it cannot fix.
  7. Report moderation and mediation results in plain words, with estimates and confidence intervals, in wording that does not claim more than the study design can show.

This course was developed by Dr. Kiffer G. Card based on Dohoo, I. R., Martin, S. W., & Stryhn, H. (2012). Methods in Epidemiologic Research. VER Inc.

Lesson 8 · HSCI 410

Mediation, Moderation and Path Analysis

The last lesson of the course asks what part a third variable plays in an association, and how to estimate and report it.

Running case

Two questions from a community connector program

Mediation

Is social support associated with fewer depressive symptoms partly through lower loneliness?

Moderation

Is the association between support and loneliness the same for younger and older adults?

The data are the 3,110 people in the 2021 wave of the Canadian Social Connection Survey with complete answers.

Lesson map

Four sections

1. The third variable

It covers confounders, mediators, colliders and effect modifiers, and the total, direct and indirect effects.

2. Moderation

It covers interaction terms, centring and simple slopes.

3. Mediation

It covers paths a, b, c and c′, the bootstrap and sensitivity analysis.

4. Path analysis

It covers lavaan, model comparison and structural equation models.

How to work through the lesson

Activities, walkthroughs and assessment

  • Four R activities use the CSCS 2021 data, loaded from GitHub with the walkthrough code.
  • The packages mediation and lavaan are installed once with install.packages().
  • Two narrated walkthroughs, Mediation and Moderation and SEM Path Analysis, show the same code line by line.
  • The final assessment has 16 questions.
Reference

Glossary: Key Terms, People & Concepts

📚 Reference page, available throughout the lesson

This glossary collects the key concepts, methods and people in this lesson. It can be used as a reference while working through the material or as a review before assessments. Typing in the search box filters the entries.

Key Concepts & Ideas
Third Variable A third variable is any variable other than the exposure and the outcome. Its role (confounder, mediator, collider or effect modifier) decides how it is handled in the analysis.
Directed Acyclic Graph (DAG) A DAG is a diagram in which each variable is a node and each assumed causal effect is an arrow, with no variable able to cause itself through a loop. Its arrows are assumptions drawn from subject knowledge.
Confounder A confounder is a common cause of the exposure and the outcome, or a proxy for one, that is not on the causal pathway. The analysis adjusts for it so that the exposure-outcome association is estimated with the confounder held constant.
Mediator A mediator lies on the pathway from the exposure to the outcome: it is affected by the exposure and in turn affects the outcome. Loneliness is the proposed mediator in this lesson.
Collider A collider is a common effect of two variables. Adjusting for it, or selecting the sample on it, opens a non-causal path between its causes, which can create a spurious association.
Effect Modifier (Moderator) An effect modifier, called a moderator in psychology, is a variable across whose levels the association between an exposure and an outcome differs in size or direction, on a stated scale (additive or multiplicative). Statistical interaction is its representation by a product term in a model, and a standard DAG does not encode it.
Total Effect (c) The total effect is the association between the exposure and the outcome when the mediator is ignored. In a linear model it equals the direct effect plus the indirect effect.
Direct Effect (c′) The direct effect is the part of the exposure-outcome association that remains when the mediator is held constant. It includes every pathway the model does not name.
Indirect Effect (a × b) The indirect effect is the part of the exposure-outcome association that runs through the mediator. In linear models it equals the product of paths a and b.
Statistical Mediation Statistical mediation describes how an association divides into direct and indirect parts without claiming a causal pathway. It is the appropriate reading of mediation estimates from cross-sectional data.
Temporal Order Temporal order is the requirement that the exposure precede the mediator and the mediator precede the outcome. A single cross-sectional survey cannot establish it.
Mediator-Outcome Confounding Mediator-outcome confounding arises when a variable affects both the mediator and the outcome. It biases the direct and indirect effects even when the exposure is randomized.
Methods & Statistical Concepts
Interaction Term An interaction term is the product of two predictors in a regression model. Its coefficient measures how much the slope of one predictor changes for each unit of the other.
Simple Slope A simple slope is the slope of the exposure at a chosen value of the moderator, such as the slope of support at age 70.
Centring Centring subtracts a chosen value, usually the mean, from a variable so that zero means average. It makes main effects in an interaction model describe slopes at meaningful values without changing the interaction.
Additive and Multiplicative Scales Interaction on the additive scale compares differences (slopes or risk differences), and interaction on the multiplicative scale compares ratios (odds or risk ratios). The same data can show interaction on one scale and not the other.
Product-of-Coefficients and Difference Methods The product-of-coefficients method estimates the indirect effect as a × b, and the difference method estimates it as c − c′. The two agree for linear models fitted to the same people.
Baron and Kenny Causal Steps The causal steps are a four-step procedure for claiming mediation from separate significance tests of paths c, a and b. They are no longer recommended as a test because they never test a × b and have low power.
Sobel Test The Sobel test divides a × b by an approximate standard error and compares it with a normal distribution. It has been largely replaced by bootstrap intervals because a × b is often skewed.
Bootstrap Confidence Interval A bootstrap confidence interval is built by resampling the data with replacement many times, re-estimating the quantity in each sample, and taking percentiles of the results.
ACME and ADE The average causal mediation effect (ACME) and the average direct effect (ADE) are the indirect and direct effects reported by mediate(). In cross-sectional data they are statistical quantities despite their names.
Proportion Mediated The proportion mediated is the indirect effect divided by the total effect. It is unstable when the total effect is small and can fall outside 0 to 1 when the parts have opposite signs.
Sensitivity Analysis (ρ) The sensitivity analysis of medsens() reports the correlation ρ between the residuals of the mediator and outcome models at which the indirect effect would fall to zero.
Path Analysis and Path Diagrams Path analysis fits a set of regressions among observed variables as one model, drawn as a diagram of rectangles, single-headed arrows (paths) and double-headed arrows (covariances).
Exogenous and Endogenous Variables An exogenous variable has no arrows pointing at it in a path model, and an endogenous variable has at least one, together with a residual.
lavaan Syntax lavaan describes a model as text: ~ for regressions, ~~ for covariances, =~ for latent variables and := for defined quantities such as an indirect effect.
Saturated Model A saturated (just-identified) model has 0 degrees of freedom and reproduces the observed covariances exactly, so its fit cannot be tested.
Nested Models and the Chi-Square Difference Test Two models are nested when one is obtained by fixing some paths of the other at zero. The chi-square difference test compares their fit, with degrees of freedom equal to the number of fixed paths.
Fit Indices (CFI, TLI, RMSEA, SRMR) Fit indices summarize how well a model reproduces the observed covariances. Common guides are CFI and TLI of 0.95 or higher, RMSEA of 0.06 or lower and SRMR of 0.08 or lower.
Standardized Coefficient A standardized coefficient expresses a path in standard deviation units, so that paths between variables on different scales can be compared.
Structural Equation Model (SEM) A structural equation model joins a measurement model, in which latent variables are measured by items, to a structural model of paths among latent and observed variables.
Latent Variable and Measurement Model A latent variable is a construct measured indirectly through several observed items. The measurement model, a confirmatory factor analysis, links it to its items.
Key People
Sewall Wright (1889–1988) Wright was an American geneticist who introduced path analysis around 1920 as a way of tracing correlations through chains of causes.
Reuben M. Baron and David A. Kenny Baron and Kenny are social psychologists whose 1986 paper on the moderator-mediator distinction set out the causal steps for mediation and became one of the most widely cited papers in psychology.
David P. MacKinnon MacKinnon is a psychologist whose comparisons of methods for testing indirect effects helped move practice from the causal steps to direct tests of a × b.
Andrew F. Hayes and Kristopher J. Preacher Hayes and Preacher are quantitative psychologists who promoted bootstrap confidence intervals for indirect effects. Hayes wrote the 2009 paper "Beyond Baron and Kenny".
Kosuke Imai Imai is a statistician and political scientist who, with Luke Keele, Dustin Tingley and colleagues, developed the mediation package and its sensitivity analysis.
Tyler J. VanderWeele VanderWeele is an epidemiologist at Harvard whose book Explanation in Causal Inference (2015) sets out the assumptions and methods of causal mediation and interaction analysis.
Judea Pearl (1936– ) Pearl is a computer scientist whose work on causal diagrams and counterfactuals underlies DAGs and the definitions of natural direct and indirect effects.
Yves Rosseel Rosseel is a statistician at Ghent University who created the lavaan package for structural equation modelling in R.
No matching entries. Try a different search term.
Section 1 of 4

What Role Does the Third Variable Play?

⏱ Estimated time: 45 minutes
Lesson 8 · Section 1

What Role Does the Third Variable Play?

A third variable can confound, mediate or collide, or it can modify an association, and each role leads to a different research question and a different analysis.

Directed acyclic graphs

Three DAG positions, and effect modification

Confounder

It causes both the exposure and the outcome: X ← C → Y.

Mediator

It lies on the pathway from the exposure to the outcome: X → M → Y.

Collider

It is caused by both the exposure and the outcome: X → Z ← Y.

Effect modification

Not a DAG position: the size of the X to Y association depends on the level of V.

From role to analysis

Each role leads to a different analysis

RoleResearch questionWhat the analyst does
ConfounderIs X associated with Y once C is held constant?Adjust for C.
MediatorHow much of the X to Y association runs through M?Split the association into direct and indirect parts.
ColliderNone: it is a consequence of X and Y.Leave it out and do not select on it.
Effect modifierDoes the X to Y association differ across levels of V?Fit an interaction or estimate within groups.
Effect decomposition

Total = direct + indirect

Decomposition in a linear model
\[ {\color{#0B7B6B}{c}} = {\color{#1D4ED8}{c'}} + {\color{#CC0033}{a \times b}} \]
c total effect of support on depressive symptoms c′ direct effect, with loneliness held constant a × b indirect effect through loneliness

Path a runs from support to loneliness, and path b runs from loneliness to depressive symptoms with support held constant.

Assumptions

Reading an indirect effect causally

  • The exposure comes before the mediator, and the mediator comes before the outcome.
  • There is no unmeasured confounding of the exposure and the outcome.
  • There is no unmeasured confounding of the exposure and the mediator.
  • There is no unmeasured confounding of the mediator and the outcome, which randomizing the exposure does not remove.
  • No confounder of the mediator and the outcome is itself caused by the exposure.
Cross-sectional data

Statistical mediation, described carefully

Suitable wording

Loneliness statistically accounted for about 41% of the association between support and depressive symptoms.

Wording to avoid

Social support reduced depression by reducing loneliness.

All three measures come from the 2021 survey wave, so the order of the variables in time cannot be established from these data.

Running example

The CSCS 2021 data

Three bar charts showing the distributions of social support (1 to 7), loneliness (3 to 9) and depressive symptoms (0 to 6) for 3,110 CSCS participants.
The three variables for the 3,110 people with complete data in the 2021 wave.
Carry forward

What to take into the next section

  • The role of a third variable is set by a DAG drawn before the analysis, and the role decides the analysis.
  • A total effect equals a direct effect plus an indirect effect in a linear model fitted to the same people.
  • A causal reading of an indirect effect needs temporal order and no unmeasured confounding, so the CSCS data support a statistical decomposition only.

Overview

This is the last lesson of HSCI 410. It follows the loneliness thread and asks how measures of loneliness and related constructs relate to one another. Most regression models relate one exposure to one outcome, with other variables added as adjustments. Many research questions are about a third variable in its own right: whether it explains part of an association, or whether an association is stronger in some groups than in others. These are questions of mediation and moderation, and the last section of the lesson shows how both can be written as a path model. This first section uses a causal diagram to decide the role a third variable plays, and it sets effect modification apart as a different kind of question. It then defines the total, direct and indirect effects that mediation analysis estimates, states the conditions under which they can be read causally, prepares the survey data so that every model uses the same people, and explains why a single survey supports only a statistical reading of mediation.

Learning Objectives

  • 1.1 Use a DAG to classify a third variable as a confounder, a mediator or a collider, state the research question each role implies, and say what the analysis does with each, including why selecting the sample on a collider creates bias.
  • 1.2 Explain why effect modification is a separate question that a standard DAG does not encode, and how it is shown and analysed instead.
  • 2.1 Define the total, direct and indirect effects, and explain how they are related in a linear model.
  • 2.2 State the conditions required to interpret an indirect effect causally, including temporal order and the absence of unmeasured mediator-outcome confounding, which randomizing the exposure does not remove.
  • 2.3 Explain why every model in a mediation analysis must use the same people, and prepare the complete cases of the CSCS 2021 variables in R.
  • 7.1 Explain why cross-sectional data support only statistical mediation, and describe a mediation result without causal overstatement.

1.1 Classifying a Third Variable with a DAG

The methods in this lesson are easier to follow when they answer a concrete question. The case below describes a community connector program whose staff have two questions about social support, loneliness, depressive symptoms and age, and it names the survey that the analyst uses to explore them. The same case and the same survey are used in every section of the lesson.

📋 The running case: a community connector program

A community connector program links adults who are isolated or under strain with local groups, volunteers and services. Its staff believe that the support people gain through the program protects their mental health, and they suspect that it does so partly by making people less lonely. They also wonder whether the program matters more for older participants. Before designing an evaluation, they ask an analyst two questions that can be explored in existing data. First, is social support associated with fewer depressive symptoms partly because people with more support are less lonely? Second, is the association between social support and loneliness the same for younger and older adults?

The analyst turns to the 2021 wave of the Canadian Social Connection Survey (CSCS), the dataset used in the narrated R walkthroughs. It contains a social support score (the Multidimensional Scale of Perceived Social Support; Zimet et al., 1988), a loneliness score (the three-item UCLA Loneliness Scale; Hughes et al., 2004), a depressive symptom score (the two-item Patient Health Questionnaire, PHQ-2; Kroenke et al., 2003) and age. In the 2021 wave, 3,110 people answered all four questions.

The first question is a mediation question, because loneliness is proposed as a step on the pathway from support to depressive symptoms. The second is a moderation question, because age is proposed as a variable that changes the size of an association. The same three variables appear in both, yet the analyses differ, because the third variable plays a different role in each. Identifying that role is the first step of the analysis, and the tool that identifies it is a causal diagram. The recall below returns to the directed acyclic graph from Lesson 1, and its retrieval question checks what happens when an analysis conditions on a collider.

Recall: Lesson 1, Section 1 (Start with a Causal Diagram)

Lesson 1, Section 1 introduced the directed acyclic graph (DAG), in which each variable is a node, each assumed causal effect is an arrow, and no variable can cause itself through a loop. Its arrows record the analyst's assumptions, which come from theory and earlier research (Greenland, Pearl and Robins, 1999). Lesson 1 named three structures: a fork (X ← C → Y), in which C is a confounder; a chain (X → M → Y), in which M is a mediator; and a collider (X → Z ← Y).

Retrieval question. What happens when an analysis adjusts for, or selects the sample on, a collider Z of X and Y?

AnswerIt opens a non-causal path between X and Y, so the two can appear associated even when neither affects the other. Lesson 1 therefore advised leaving colliders out of the model and watching for them in the way people were selected into a study.

With an exposure X and an outcome Y in place, a DAG distinguishes three positions for a third variable. What separates the positions is the direction of the arrows that connect the third variable to X and to Y, and each position calls for a different decision about the model. A confounder is a common cause of the exposure and the outcome (X ← C → Y). By this we mean that C sits upstream of both X and Y, so it can make them move together even if X has no effect on Y at all. Because part of the crude association may come from C rather than from X, the analysis adjusts for it, which removes that shared influence. A mediator, in contrast, lies on the pathway (X → M → Y): the exposure changes the mediator, and the mediator in turn changes the outcome. Here the third variable is part of the story of how X relates to Y, not a rival explanation for it. The analysis therefore uses the mediator to split the association into a part that runs through it and a part that does not. For the same reason, it leaves the mediator out of a model whose aim is the total effect, because holding M constant would block one of the routes by which X reaches Y. Finally, a collider is a common effect (X → Z ← Y), in which both arrows point into the third variable. A collider does not create an association between X and Y on its own, but adjusting for it or selecting the sample on it can create one that is not there in the population. The analysis therefore leaves it out of the model and does not select the sample on it. Panels A to C of Figure 8.1 draw the three positions for the running case; panel D, which concerns effect modification, is taken up in 1.2.

A. Confounder Health condition Social support Depression Adjust for it. B. Mediator Loneliness Social support Depression Split the association. C. Collider Program referral Social support Depression Do not select or adjust on it. D. Effect modification by age (V) Stratum: V = under 50 Social support Loneliness −0.50 Stratum: V = 50 and over Social support Loneliness −0.81 Compare the association across strata of V.
Figure 8.1. The three DAG positions of a third variable (red boxes) relative to an exposure and an outcome (teal boxes), and effect modification. In panel C, the double box marks an analysis restricted to people who were referred, so the collider here is selection into the sample (S), and the dashed line is the spurious association that this restriction creates. A standard DAG does not encode effect modification, so panel D draws the diagram within each stratum of the modifier V (age group) and labels each arrow with the support slope estimated in Section 2.

Click each of the three cards below to see an example of each position from the running case, the research question that the position implies and what it asks of the analysis.

ConfounderClick to explore
MediatorClick to explore
ColliderClick to explore

Two of these roles are easily confused in practice, because a mediator and a confounder look alike in the data. The direction of one arrow separates them.

Mediator or Confounder

A mediator and a confounder are both associated with the exposure and with the outcome, so they cannot be told apart from correlations alone. The difference lies in the direction of the arrow between the exposure and the third variable. A confounder affects the exposure, and the analysis adjusts for it. A mediator is affected by the exposure, and adjusting for it when the total effect is the target removes part of the association that the study set out to estimate. Deciding which arrow is more plausible requires subject knowledge about timing and mechanism, and in some studies a variable could play either role.

Real diagrams often contain several third variables at once, and each is classified in the same way. A diagram can have two confounders that are both adjusted for, or two mediators that each lie on a separate pathway and are both left out of the model for the total effect. Colliders deserve particular care, because they often hide in the way people come to be in the data. Referral to a program, the example in panel C, is one. Others are being re-interviewed at a follow-up, being present on the day a survey was completed in class, or still working in a unit when staff were surveyed. If the exposure and the outcome both affect whether a person ends up in the data (for example, if people with high exposure and poor outcomes are more likely to drop out), then analysing only the people who remain conditions on a collider. The exposure and the outcome can then appear associated, or their association can be distorted, among the people analysed, and adjusting for other variables cannot undo this selection bias. It is addressed through the design (recruiting from a population frame and keeping people in the study) or, when that is not possible, described as a limitation and explored with a sensitivity analysis.

The three DAG positions describe where a third variable sits on the paths between an exposure and an outcome. The program's second question asks something that none of these positions can express.

1.2 Effect Modification as a Separate Question

Effect modification is a question about the size of the X to Y effect across levels of a variable V: is the association stronger in some groups than in others? By this we mean that V does not need to sit on any path between X and Y; instead, the strength of the X to Y association depends on which value of V a person has. For example, an extra point of social support might go with a large drop in loneliness among older adults but a smaller drop among younger adults. This is a different kind of question from the three DAG positions in 1.1, which ask where a variable sits, not whether an association changes size. A standard DAG does not encode it, because an arrow states only that an effect exists, not how large it is, so the same arrow would be drawn whether the effect were large, small or different between groups. Effect modification is therefore shown by a note on the diagram or by drawing the diagram within each stratum of V. Panel D of Figure 8.1 takes the second approach for the running case. It draws the arrow from support to loneliness once for adults under 50 and once for adults aged 50 and over, and labels each arrow with the support slope estimated in Section 2, −0.50 and −0.81. Effect modification is analysed by fitting an X × V interaction term or by estimating the association separately in each group. Click the card below for the research question that an effect modifier implies and the way it is analysed.

Effect ModifierClick to explore

Table 8.1 brings the four roles together in one place. For each role it gives the position in the DAG, the research question the role implies and what the analysis does with the variable. The same variable can be a confounder, an effect modifier, both or neither, so a variable is classified separately for each question being asked.

Table 8.1. The four roles a third variable can play, the research question each implies and what the analysis does.

RolePosition in the DAGResearch question it impliesWhat the analysis does
Confounder (C)X ← C → YIs X associated with Y when C is held constant?Adjusts for C.
Mediator (M)X → M → YHow much of the X to Y association runs through M?Splits the total into direct and indirect parts.
Collider (Z)X → Z ← YNone; Z is a consequence of X and Y.Leaves Z out of the model and does not select on it. In the referral example the collider is selection into the sample (S).
Effect modifier (V)Not a DAG position; shown by a note or by drawing the DAG within each stratum of VDoes the X to Y association differ across levels of V?Fits an X × V interaction or stratifies by V.

Interactive 8.1 gives practice in all four distinctions drawn in Table 8.1. It presents eight scenarios, five built on the running case and three from other areas of public health, each naming an exposure, an outcome and a third variable. Choose the DAG position the third variable takes (confounder, mediator or collider), or choose effect modifier when the scenario is about the size of the association, which a DAG does not show. Feedback appears after each choice.

📊 Interactive 8.1: Role sorter: eight scenarios

1. Exposure: social support. Outcome: depressive symptoms. Third variable: a long-term health condition, which can limit social contact and can also raise depressive symptoms.

2. Exposure: social support. Outcome: depressive symptoms. Third variable: loneliness, which may fall when support rises and may in turn lower depressive symptoms.

3. Exposure: social support. Outcome: loneliness. Third variable: age group, because the association appears stronger among adults aged 50 and over than among younger adults.

4. Exposure: social support. Outcome: depressive symptoms. Third variable: referral to the program, which is more likely for people with low support and for people with depressive symptoms. The analysis includes referred people only.

5. Exposure: social support. Outcome: depressive symptoms. Third variable: household income, which affects the time and resources people have for social contact and also affects mental health through financial strain.

6. Exposure: joining a walking group. Outcome: blood pressure six months later. Third variable: weekly minutes of physical activity at three months.

7. Exposure: a smoking cessation program. Outcome: quitting at one year. Third variable: living with a partner who does not smoke, because the program appears to work better for people who do.

8. Exposure: severe infection. Outcome: frailty. Third variable: hospital admission, which is more likely for people with a severe infection and for people who are frail. A study of admitted patients only finds that infection and frailty are negatively associated.

0 of 8 scenarios sorted correctly.

The DAG has now fixed the role of each third variable in the running case. Loneliness is the proposed mediator of the association between support and depressive symptoms, and age is a proposed effect modifier of the association between support and loneliness. The next subsection takes the mediator and shows how the association it carries can be divided.

2.1 Total, Direct and Indirect Effects

Once loneliness has been identified as a proposed mediator, the association between support and depressive symptoms can be divided into parts. The total effect is the association between the exposure and the outcome when the mediator is ignored. By this we mean the overall difference in depressive symptoms between people whose support scores differ by one point, whatever route that difference takes. The total is then divided into two parts. The indirect effect is the part of the total that runs through the mediator: support is associated with loneliness, and loneliness is in turn associated with depressive symptoms, so some of the total travels along that chain. The direct effect is the part that remains when the mediator is held constant. In other words, it compares people with different support scores but the same loneliness score, so whatever association is left cannot be passing through loneliness. Because the model names only one mediator, the direct effect is a catch-all: it includes every other pathway the model does not name, such as any route through physical activity or sleep. The word "effect" is the conventional statistical name for these quantities. In cross-sectional data such as the CSCS, each one is an association, and it describes a cause only under the conditions set out in 2.2.

Mediation analysis labels the paths with letters. Path a runs from the exposure to the mediator. Path b runs from the mediator to the outcome, with the exposure held constant. Path c is the total effect, and path c′ (read "c prime") is the direct effect. Figure 8.2 draws these paths for the running case, with the total effect in the upper diagram and its division into direct and indirect parts in the lower one.

Total effect Social support (X) Depression (Y) c (total) Direct and indirect effects Loneliness (M) Social support (X) Depression (Y) a b c′ (direct)
Figure 8.2. The total effect (path c, top) and its decomposition (bottom). The indirect effect is the product of paths a and b, and the direct effect is path c′.

When the mediator and the outcome are continuous and every model is a linear regression fitted to the same people, the parts add up exactly. Equation 8.1 expresses this decomposition in the path labels of Figure 8.2.

Decomposition of the total effect in a linear model
\[ {\color{#0B7B6B}{c}} = {\color{#1D4ED8}{c'}} + {\color{#CC0033}{a \times b}} \]Eq 8.1
The total effect c equals the direct effect c′ plus the indirect effect a × b. Rearranged, the indirect effect is also c − c′, which is called the difference method. Section 3 calculates both in the CSCS data.

The causal-inference literature defines these quantities more generally with counterfactuals. A counterfactual is the value an outcome would have taken under a condition that did not actually occur for that person. Using this idea, the indirect effect is the change in the outcome that would follow if the mediator shifted from the value it would take at one level of the exposure to the value it would take at another, with the exposure itself held fixed (Robins and Greenland, 1992; Pearl, 2001). For example, imagine keeping a person's support where it is but moving their loneliness to the level it would have reached if their support had been one point higher; the resulting change in depressive symptoms is the indirect effect. The direct effect is defined the other way round: the exposure changes while the mediator is kept at the value it would have had without that change. The advantage of these definitions is that they do not depend on a particular model, so they still apply when the outcome is binary or when the model contains interactions, settings in which the simple product a × b no longer has a clear meaning. They are the basis of the mediate() function used in Section 3. For linear models without interactions, they give the same numbers as a × b and c′, so in the running case the two approaches agree.

The decomposition in Equation 8.1 is arithmetic, and it holds in any dataset in which the linear models are fitted to the same people. Whether the indirect part describes a causal pathway is a separate matter, which depends on the conditions set out next.

2.2 Conditions for a Causal Reading of an Indirect Effect

An estimated indirect effect describes a causal pathway only if five conditions hold (VanderWeele, 2015): the exposure comes before the mediator and the mediator before the outcome (temporal order); there is no unmeasured confounding of the exposure and the outcome, of the exposure and the mediator, or of the mediator and the outcome; and no mediator-outcome confounder is itself affected by the exposure. Notice that confounding has to be ruled out for three separate pairs of variables, not just one. This is because a mediation analysis estimates three relationships (exposure to outcome, exposure to mediator and mediator to outcome), and an unmeasured common cause of any pair would bias the piece of the decomposition that depends on it. None of the conditions can be confirmed from the data alone, because an unmeasured variable leaves no visible trace in the output, which is why the DAG and the study design carry so much of the argument. Expand each panel of the accordion below to see what a condition requires and how it applies to the running case.

1. Temporal order

The exposure must occur before the mediator, and the mediator before the outcome. A cohort that measures support at one visit, loneliness at a later visit and depressive symptoms later still provides this order. A single survey that asks about all three at once does not.

2. No unmeasured exposure-outcome confounding

Every common cause of the exposure and the outcome must be measured and adjusted for. This is the same condition that any estimate of a total effect requires.

3. No unmeasured exposure-mediator confounding

Every common cause of the exposure and the mediator must be measured and adjusted for, so that path a describes the effect of the exposure on the mediator.

4. No unmeasured mediator-outcome confounding

Every common cause of the mediator and the outcome must be measured and adjusted for. This condition is the easiest to overlook, because randomizing the exposure does not satisfy it. In a trial that assigns people to the community connector program at random, loneliness is still not assigned at random. A history of depression, for example, could raise both loneliness and later depressive symptoms. When such a variable is left out, the estimate of path b is biased, and so are the direct and indirect effects (Cole and Hernán, 2002).

5. No mediator-outcome confounder affected by the exposure

No common cause of the mediator and the outcome may itself be caused by the exposure. If support affects physical activity, and physical activity affects both loneliness and depressive symptoms, the usual direct and indirect effects cannot be separated by regression adjustment alone. The reason is that physical activity now plays two roles at once. It is a confounder of loneliness and depressive symptoms, so it ought to be adjusted for; yet it is also on a pathway from support to depressive symptoms, so adjusting for it removes part of the effect being decomposed. Ordinary regression cannot do both jobs at the same time, and more specialized methods are needed when such a variable is present.

The fourth condition is the one most easily overlooked, because randomizing the exposure does not satisfy it: a trial can assign people to the program at random, but it cannot assign their loneliness at random, so a common cause such as a history of depression can still bias path b and with it the direct and indirect effects. Because this condition cannot be checked, careful mediation analyses report how strong an unmeasured mediator-outcome confounder would need to be to remove the indirect effect. Section 3 runs this sensitivity analysis with the medsens() function of the mediation package.

The first condition, temporal order, is a matter of study design, and 7.1 asks whether the CSCS can meet it. Before any of these effects can be estimated, however, the data must be prepared so that the models being compared describe the same people.

2.3 Keeping the Same People in Every Model

Mediation compares coefficients across several models: the total-effect model, the mediator model and the outcome model. Equation 8.1 holds exactly only when all of them are fitted to the same people. This is because the decomposition is a statement about one set of data: the total effect splits into a direct and an indirect part only if each part is estimated from the same observations. If one model includes people that another leaves out, the coefficients describe slightly different groups, and the pieces no longer have to add up. In R, lm() drops only the people who are missing a variable in that particular model, so with incomplete data each model can quietly use a different sample. In the CSCS 2021 wave, 829 people are missing a support score, 462 a loneliness score and 743 a depressive symptom score. Fitted to these data as they stand, the total-effect model (depressive symptoms on support) uses 3,133 people and the mediator model (loneliness on support) uses 3,191, so their coefficients would describe different samples and c would no longer equal c′ + a × b.

The remedy is to put the variables the analysis needs into one small data frame, run na.omit() once before any model is fitted, and confirm the sample size with nrow(). In the CSCS this keeps the 3,110 people who answered all four questions (support, loneliness, depressive symptoms and age), and every model in Sections 1 to 3 uses these 3,110. When numbers differ slightly between analyses, the sample size is the first thing to check: the path models of Section 4 add anxiety symptoms and use 3,099 people, which is why their estimates differ in the third decimal place.

Figure 8.3 shows the three scores for the 3,110 people with complete data. Support is concentrated between 4 and 6 on its 1 to 7 scale, loneliness spreads across its 3 to 9 range, and depressive symptoms are most often between 0 and 3 on the 0 to 6 PHQ-2 scale.

Three bar charts. Panel A shows social support scores, rounded, with most people between 4 and 6. Panel B shows UCLA loneliness scores from 3 to 9, most often 5 or 6. Panel C shows PHQ-2 depressive symptom scores from 0 to 6, most often 0 to 3.
Figure 8.3. The distributions of social support (rounded to whole points for display), loneliness and depressive symptoms for the 3,110 CSCS 2021 participants with complete data on all four variables.

Activity 8.1, at the end of 7.1, carries out these steps in R. Before running it, one more question about the data needs an answer: what kind of conclusion can a single survey support?

7.1 Statistical Mediation in Cross-Sectional Data

The CSCS 2021 wave measured social support, loneliness and depressive symptoms in the same survey, at the same time. The first condition of 2.2, temporal order, therefore cannot be established. Each arrow in the mediation diagram could plausibly run in the other direction. People with depressive symptoms may withdraw from others and feel lonelier, and they may also perceive the support around them as weaker than others would judge it. Maxwell and Cole (2007) showed that mediation estimates from cross-sectional data can differ substantially from the longitudinal processes they are meant to describe.

The analysis in this lesson is still informative. It shows whether the pattern of associations is consistent with the program's explanation, and how large the indirect association is. That information can justify a longitudinal evaluation of the program, in which support, loneliness and depressive symptoms are measured at successive times. It is reported as a statistical decomposition of an association, and causal language is kept for designs in which the conditions of 2.2 are plausible.

Table 8.2 sets the two kinds of wording side by side, using the CSCS results that Section 3 estimates. The left column describes a statistical decomposition, and the right column claims a causal pathway that the data cannot show. Words such as "statistically accounted for", "was associated with" and "is consistent with" suit these data; "reduced", "caused" and "is the mechanism by which" do not.

Table 8.2. Wording suited to a cross-sectional mediation result, set against wording that claims a causal pathway.

Wording suited to cross-sectional dataWording that claims a causal pathway
Loneliness statistically accounted for about 41% of the association between social support and depressive symptoms.Social support reduced depressive symptoms by reducing loneliness.
The indirect association through loneliness was −0.23 PHQ-2 points per point of support.Each extra point of support caused a 0.23-point fall in depressive symptoms through loneliness.
The pattern of associations is consistent with a pathway through loneliness, which a longitudinal study could test.Loneliness is the mechanism by which support protects mental health.

Activity 8.1 puts 2.3 and this subsection into practice. It loads the CSCS data and prepares the variables with the same code as the narrated walkthrough Mediation and Moderation, so that every number in this lesson can be reproduced. Run it along with the text: it shows how many people each model uses before and after na.omit() and prints the correlations of the three scores, and its questions ask you to explain why every model needs the same people and to word a result to suit a single survey.

R Activity 8.1: load the CSCS data and keep the same people in every model

Text version of the activity: the code of the run-along script, its console output and notes on reading it.

github_url <- "https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"
load(url(github_url))                      # survey data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
dim(data)                                  # people (rows) and variables (columns)
Console output
[1] 4045 3247

The file is read straight from GitHub, so no file needs to be downloaded, although load() takes a few seconds because the file is large. It creates a data frame called data. The 2021 wave holds 4,045 people (rows) and 3,247 variables (columns); the data[ , ] line keeps the rows whose survey year is 2021, so that each person appears once.

# support:    social support (MSPSS), 1 to 7, higher = more support
# loneliness: UCLA 3-item Loneliness Scale, 3 to 9, higher = lonelier
# depression: PHQ-2 depressive symptoms, 0 to 6, higher = more symptoms
med_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,
  depression = data$WELLNESS_phq_score,
  age        = data$DEMO_age)
summary(med_data)
Console output
support loneliness depression age Min. :1.000 Min. :3.000 Min. :0.000 Min. : 16.0 1st Qu.:4.250 1st Qu.:4.000 1st Qu.:1.000 1st Qu.: 28.0 Median :5.000 Median :6.000 Median :2.000 Median : 34.0 Mean :4.932 Mean :5.575 Mean :2.066 Mean : 39.8 3rd Qu.:5.667 3rd Qu.:7.000 3rd Qu.:3.000 3rd Qu.: 52.0 Max. :7.000 Max. :9.000 Max. :6.000 Max. :100.0 NAs :829 NAs :462 NAs :743

The data.frame() call copies four variables into a small data frame with short names. The summary shows a mean support score of 4.93 (on its 1 to 7 scale), a mean loneliness score of 5.58 (3 to 9) and a mean depressive symptom score of 2.07 (0 to 6). The NAs row counts missing answers: 829 for support, 462 for loneliness and 743 for depressive symptoms. Age has no missing values.

nobs(lm(depression ~ support, data = med_data))   # people in a total-effect model
nobs(lm(loneliness ~ support, data = med_data))   # people in a mediator model
med_data <- na.omit(med_data)              # keep people with no missing values
nrow(med_data)                             # people in every model of the lesson
Console output
[1] 3133 [1] 3191 [1] 3110

lm() drops only the people who are missing a variable in that model, and nobs() reports how many people a model used: 3,133 for the total-effect model (depressive symptoms on support) and 3,191 for the mediator model (loneliness on support). Mediation compares coefficients across these models, so they must describe the same people. na.omit(), run once before any model is fitted, keeps the 3,110 people who answered all four questions, and every model in the lesson uses these 3,110.

round(cor(med_data[, c("support", "loneliness", "depression")]), 2)
Console output
support loneliness depression support 1.00 -0.40 -0.38 loneliness -0.40 1.00 0.47 depression -0.38 0.47 1.00

Reading the output. Support is negatively correlated with loneliness (−0.40) and with depressive symptoms (−0.38), and loneliness is positively correlated with depressive symptoms (0.47). These signs fit the program's proposed pathway, in which more support goes with less loneliness and less loneliness goes with fewer symptoms, but correlations are symmetric and the three scores come from one survey, so they cannot show the direction of any arrow.

Files for this activity Data Code Answer key

R Reflect on what you just ran

Answer each question from your own output, as on the final exam: give the number, say what it means and word the conclusion to suit a single survey.

1. The summary shows that 829 people are missing a support score, 462 a loneliness score and 743 a depressive symptom score. Fitted to med_data before na.omit(), the total-effect model uses 3,133 people and the mediator model 3,191. Explain why this is a problem for a mediation analysis, and say which line of the script fixes it and how many people it leaves.

Model answerEach lm() drops only the people who are missing one of its own variables, so the total-effect model uses 3,133 people and the mediator model 3,191: the coefficients would describe different samples. Mediation compares coefficients across the total-effect, mediator and outcome models, and the total effect equals the direct effect plus the indirect effect (c = c′ + a × b) only when every model is fitted to the same people. The fix is the line med_data <- na.omit(med_data), run once before any model is fitted, which keeps the people with no missing values on all four variables. Running nrow(med_data) afterwards confirms that 3,110 people remain, and every model in the lesson uses these 3,110.

2. Report the three correlations and say what their signs mean for the community connector program's proposed pathway. A draft report says: “Social support lowers depressive symptoms by reducing loneliness.” Rewrite this sentence so that it suits these data, and explain why the correlations cannot show which way the arrows run.

Model answerSupport is correlated −0.40 with loneliness and −0.38 with depressive symptoms, and loneliness is correlated 0.47 with depressive symptoms. People with more support tend to be less lonely and to report fewer symptoms, and lonelier people tend to report more symptoms, so the signs are consistent with the proposed pathway from support through loneliness to depressive symptoms. A suitable rewrite is “The pattern of associations is consistent with a pathway from social support through loneliness to depressive symptoms, which a longitudinal study could test”. The draft claims a cause that these data cannot show: a correlation is symmetric and says nothing about which variable comes first, and all three scores were measured in the same 2021 survey, so temporal order cannot be established; people with depressive symptoms may withdraw from others, feel lonelier and perceive less support. Data with support measured first, loneliness later and depressive symptoms later still would establish temporal order.

3. Run your own code: at the end of the script, type the three lines below and run them. Report the total effect c and the direct effect c′ of support from the first two lines, and the indirect association by the difference method and its share of the total from the third, and say what each means. If a trial assigned people to the community connector program at random, which condition would still be needed to read the indirect effect through loneliness causally?
(c_total <- coef(lm(depression ~ support, data = med_data))[["support"]])
(c_direct <- coef(lm(depression ~ support + loneliness, data = med_data))[["support"]])
c(indirect = c_total - c_direct, share = (c_total - c_direct) / c_total)

Model answerThe first line prints the total effect, c = −0.560: each one-point higher support score is associated with a depressive symptom score 0.56 points lower. The second prints the direct effect, c′ = −0.331, the association with loneliness held constant. The third prints the indirect association by the difference method, c − c′ = −0.229 points per point of support, and its share of the total, 0.41: loneliness statistically accounted for about 41% of the association between support and depressive symptoms. The subtraction is valid because both models use the same 3,110 people. A trial that assigned people to the program at random would still need no unmeasured confounding of the mediator and the outcome: loneliness itself would not be assigned at random, so a common cause such as a history of depression could raise both loneliness and later depressive symptoms and bias path b, and with it the direct and indirect effects.
Saved.

The correlations at the end of Activity 8.1 have the signs that the program's proposed pathway predicts, yet, because they are symmetric and come from one survey, they cannot show the direction of any arrow. That is the statistical reading of mediation that this subsection described.

This section has identified the role of each third variable in the running case, defined the total, direct and indirect effects, stated the conditions for a causal reading, prepared the 3,110 complete cases in R and set out what a single survey can show. Section 2 takes up the second question of the running case, whether the association between support and loneliness differs by age. The key takeaways and knowledge check below review this material.

Key Takeaways

  • 1.1 A third variable can sit in one of three places in a causal diagram, and its place tells you what to do with it. A confounder is a common cause of the exposure and the outcome (X ← C → Y), so you adjust for it; a mediator lies on the pathway (X → M → Y), so you use it to split the association into direct and indirect parts and leave it out of a model for the total effect; and a collider is a common effect (X → Z ← Y), so you leave it out of the model and do not select the sample on it. A mediator and a confounder look alike in the correlations, so the deciding question is the direction of the arrow between the exposure and the third variable, which you settle from timing and subject knowledge before fitting any model. When a question asks for a role, give the position, the research question it implies and what the analysis does with the variable, as in Table 8.1. Watch for colliders hidden in how people came to be in the data (referral to a program, being re-interviewed at follow-up, still working in a unit when staff were surveyed): analysing only those people can create a spurious association that adjusting for other variables cannot remove, so call it selection bias and say that it is addressed through the design.
  • 1.2 Effect modification asks a different kind of question: whether the size of the exposure-outcome association differs across levels of a variable V, such as age group. A standard DAG cannot show this, because an arrow says only that an effect exists and not how large it is, so you mark it with a note on the diagram or draw the diagram within each stratum of V, as in panel D of Figure 8.1. It is analysed with an X × V interaction term or by estimating the association separately in each group. In a scenario, wording such as "the association appears stronger in" or "the program works better for" points to an effect modifier, not to a confounder or a mediator. The same variable can be a confounder, a modifier, both or neither, so classify it separately for each question being asked.
  • 2.1 Once you have identified a mediator, the association between the exposure and the outcome can be split into parts. The total effect (path c) is the association when the mediator is ignored, the direct effect (path c′) is what remains when the mediator is held constant, and the indirect effect is the part that runs through the mediator, the product of path a (exposure to mediator) and path b (mediator to outcome, with the exposure held constant). When every model is a linear regression fitted to the same people, the parts add up exactly, c = c′ + a × b, so the indirect effect can also be found as c − c′. When you read the R output, a quick check is that the direct and indirect parts it reports make up the total: in the CSCS, the direct effect of −0.331 and the indirect effect of −0.229 together give the total of −0.560. Keep in mind that "effect" is only the conventional name; in cross-sectional data each of these quantities is an association.
  • 2.2 An indirect effect can be read as a causal pathway only if several conditions hold, and none of them can be confirmed from the data alone. The exposure must come before the mediator and the mediator before the outcome (temporal order); there must be no unmeasured confounding of the exposure and outcome, of the exposure and mediator, or of the mediator and outcome; and no mediator-outcome confounder may itself be affected by the exposure. The mediator-outcome condition is the one most often missed, because randomizing the exposure does not randomize the mediator: in a trial that assigns people to the connector program at random, a history of depression could still raise both loneliness and later depressive symptoms and bias path b and the direct and indirect effects. When a question asks whether a trial or a survey shows a mechanism, name the missing condition and a plausible confounder of the mediator and the outcome. This is also why careful analyses add a sensitivity analysis for that condition.
  • 2.3 Mediation compares coefficients from several models (the total-effect, mediator and outcome models), so every model must be fitted to exactly the same people. If one model drops people who are missing a loneliness score and another keeps them, the coefficients describe different samples and c will no longer equal c′ + a × b. The practical step is to put the variables you need in one small data frame, run na.omit() once before fitting anything, and confirm the sample size with nrow(); in the CSCS 2021 wave this leaves 3,110 people. When numbers differ slightly between analyses, check the sample size first: the path models later in the lesson use 3,099 people because anxiety symptoms were added, which is why their estimates differ in the third decimal place.
  • 7.1 The CSCS measured support, loneliness and depressive symptoms in the same survey at the same time, so it cannot establish temporal order, and every arrow could plausibly run the other way (people with depressive symptoms may withdraw from others and feel lonelier). The analysis is still informative, but it supports only statistical mediation: a description of how an association divides, not evidence of a mechanism. In your own answers, use wording such as "loneliness statistically accounted for about 41% of the association" or "the pattern is consistent with a pathway through loneliness", and avoid "reduced", "caused" or "is the mechanism by which". A strong final sentence names what a longitudinal design, with the exposure, mediator and outcome measured at successive times, would add.
Knowledge check: this section

1. A community garden program asks whether weekly gardening hours (X) are associated with depressive symptoms six months later (Y). The analyst's DAG has these arrows: chronic pain → gardening hours and chronic pain → symptoms; gardening hours → social contact → symptoms; gardening hours → symptoms; and gardening hours → attended the six-month check-in ← symptoms. Symptoms were recorded only for people who attended the check-in. Which analysis plan for the total effect of gardening hours follows from the DAG?

Social contact has an arrow in from gardening and an arrow out to symptoms, so it is a mediator, and adjusting for it removes part of the total effect. Attendance needs attention because it is a collider, and analysing attenders only already conditions on it.
Chronic pain causes both exposure and outcome, so it is a confounder; social contact lies on the pathway, so it is a mediator left out of the total-effect model; attendance receives arrows from both, so it is a collider, and selecting attenders can distort the association.
This swaps the first two roles. Chronic pain sends arrows into both gardening and symptoms, making it a confounder, and social contact lies between them, making it a mediator. Adjusting for a collider does not remove collider bias; conditioning on it creates the problem.
The first two roles are right, but adjusting for the mediator would estimate the direct effect, not the total effect. Attendance is a collider, a common effect of exposure and outcome, not an effect modifier, so an interaction does not address it.
The correct plan adjusts for chronic pain only and treats attendance as a collider. Read the arrows into and out of each third variable. Chronic pain has arrows into both gardening hours and symptoms (X ← C → Y), so it is a confounder and is adjusted for. Social contact has an arrow in from gardening and an arrow out to symptoms (X → M → Y), so it is a mediator; adjusting for it would remove the part of the association that runs through it and leave the direct effect instead of the total. Attendance has arrows in from both gardening and symptoms (X → Z ← Y), so it is a collider, and because only attenders have symptom data, the analysis is already restricted to one level of it; this selection can create or distort an association, and no adjustment undoes it (it is addressed by following up everyone, or reported as a limitation). The last option is tempting because social contact is clearly related to symptoms, but that is exactly why adjusting for a mediator changes the question. (Section 1, 1.1 Classifying a Third Variable with a DAG, the callout "Mediator or Confounder" and the paragraph after it, and Table 8.1; Objective 1.1)

2. The garden program also asks whether the association between gardening hours and depressive symptoms is stronger for people who live alone than for people who live with others. A colleague proposes to show this by drawing an arrow from living alone to depressive symptoms in the DAG and adjusting for living alone. Which response is correct?

An arrow in a DAG states only that one variable affects another, so it cannot show that an association is stronger in one group. Adjusting for living alone fits one common gardening slope, so it does not test whether the slopes differ.
A mediator lies on the pathway from exposure to outcome and is used to split the association. The question here is whether the size of the association differs between groups, which is effect modification, not mediation.
A collider is a common effect of the exposure and the outcome, and nothing in the stem makes living alone one. The question is whether the association differs in size between groups, which needs an interaction or a within-group estimate.
Effect modification concerns the size of an association, which a DAG arrow cannot show, so it is noted on the diagram or the diagram is drawn within each group. An interaction term, or an estimate in each group, tests whether the slopes differ.
The correct response is that this is effect modification, which is analysed with an interaction or within groups. The stem asks whether the association between gardening and symptoms differs in size between two groups. An arrow in a DAG states only that one variable affects another, so it cannot show that an association is stronger in one group; the modification is shown by a note on the diagram or by drawing the diagram within each group. The tempting first option fails because adjusting for living alone fits one common gardening slope for both groups, so it does not test whether the slopes differ; a gardening × living alone interaction term, or a separate estimate in each group, does. Living alone may also be a confounder that is adjusted for, but that answers a different question. (Section 1, 1.2 Effect Modification as a Separate Question, Figure 8.1, panel D, and Table 8.1; Objective 1.2)

3. An analyst asks whether physical activity (M) lies on the pathway from gardening hours (X) to depressive symptoms (Y). She fits the total-effect model to all 1,500 people with symptom data, and the mediator and outcome models to the 1,200 people who also reported their activity. R prints the number of people in each model and the indirect effect by both methods, and she reports the indirect effect as −0.20. What is the best judgement of this result?

> c(total = nobs(model_total), mediator = nobs(model_a), outcome = nobs(model_b))
   total mediator  outcome
    1500     1200     1200
> a * b                 # product of coefficients
gardening
    -0.15
> c_total - c_direct    # difference method
gardening
     -0.2 
The decomposition of the total into direct and indirect parts holds exactly only when the linear models are fitted to the same people. Here the total-effect model used more people, so the two methods disagree until all three models use the same complete cases.
The product and difference methods estimate the same indirect effect, and in linear models fitted to the same people they agree exactly. Their disagreement here signals that the models used different people, not that either value is acceptable.
The direct and indirect parts add up to the total, so the indirect effect is the total minus the direct effect, not the sum of the total and the direct effect. The problem in the output is that the models used different people.
The indirect effect is the product of path a and path b, not their ratio. The disagreement between the two printed estimates comes from fitting the models to different people.
The correct judgement is that the two estimates disagree because the models use different people. The output gives the indirect effect by the product method (a × b, −0.15) and by the difference method (c − c′, −0.20), and the nobs() line shows that the total-effect model used 1,500 people while the mediator and outcome models used 1,200. The decomposition c = c′ + a × b holds exactly only when the linear models are fitted to the same people, so here the two methods no longer agree. Running na.omit() once to keep the 1,200 complete cases, and refitting the total-effect model to them, restores the decomposition. The second option is tempting, but both methods estimate the same indirect effect and agree whenever every linear model uses the same people. (Section 1, 2.1 Total, Direct and Indirect Effects and Eq 8.1; 2.3 Keeping the Same People in Every Model and Activity 8.1; Objectives 2.1 and 2.3)

4. A trial randomly assigns 600 isolated adults to a community connector program or to usual services. Loneliness is measured at three months and depressive symptoms at six months. The report states: "Because the program was randomized, the indirect effect through loneliness can be read causally." Which condition for a causal reading does the randomization leave unsecured?

The design already secures temporal order: the program is assigned first, loneliness is measured at three months and symptoms at six months. The condition left open concerns confounding of the mediator and the outcome.
Random assignment balances every cause of who receives the program, so it removes confounding of the program with depressive symptoms. That condition is secured by the design.
Loneliness was not assigned at random, so a common cause of loneliness and later symptoms, such as a history of depression, can still bias path b and with it the direct and indirect effects. Randomizing the program cannot remove this.
Because the program was randomized, nothing that causes loneliness can also determine who receives the program. Confounding of the program and loneliness is therefore removed by the design.
The unsecured condition is no unmeasured confounding of loneliness and depressive symptoms. Check each condition against the design. Random assignment balances every cause of who receives the program, so it removes confounding of the program with depressive symptoms and with loneliness, and the measurement times (program first, loneliness at three months, symptoms at six months) give temporal order. Loneliness itself was not assigned at random, so a common cause of loneliness and later symptoms, such as a history of depression, can still bias path b and with it the direct and indirect effects. The temporal-order option is tempting because order is a key condition, but this design already provides it. This is why a sensitivity analysis is reported with a mediation result even from a trial. (Section 1, 2.2 Conditions for a Causal Reading of an Indirect Effect, accordion panel 4 and the paragraph after it; Objective 2.2)

5. A single cross-sectional survey of 1,800 workers measured noise exposure at work, job stress and systolic blood pressure, and both mediation models were adjusted for age and gender. The indirect association of noise with blood pressure through stress was 0.8 mmHg per 10 dB (95% bootstrap CI 0.4 to 1.2), about 25% of the total association. Which sentence suits the report, for the right reason?

An interval that excludes zero shows that the indirect association is unlikely to be due to sampling variation alone, but it says nothing about direction. One survey cannot show that noise came before stress, so causal wording is not supported.
Associational wording fits a single cross-sectional survey, which cannot establish that noise preceded stress and stress preceded blood pressure. The 25% describes how the association divides statistically, not a causal pathway.
The bootstrap changes only how uncertainty is estimated. It does not establish temporal order or remove unmeasured confounding, so it cannot show that stress is the mechanism.
Adjusting for age and gender does not rule out unmeasured confounding of stress and blood pressure, and a single survey cannot establish temporal order. A claim about what reducing noise would do is a causal claim the design cannot support.
The suitable sentence describes a statistical decomposition ("statistically accounted for"). The facts needed are that all three variables come from one survey at one time and that the interval excludes zero. An interval that excludes zero shows that the indirect association is unlikely to be due to sampling variation alone, but it says nothing about direction: the survey cannot show that noise came before stress and stress before blood pressure, and adjusting for age and gender cannot rule out unmeasured confounding of stress and blood pressure. The other three sentences all claim a causal pathway; the first is the most tempting because it cites the interval, but a clearly non-zero indirect association is still an association. (Section 1, 2.2 Conditions for a Causal Reading of an Indirect Effect; 7.1 Statistical Mediation in Cross-Sectional Data and Table 8.2; Objectives 2.2 and 7.1)

6. A health authority invited 3,500 adults aged 65 and over to a single clinic visit with a hearing test and a cognitive test (scored 0 to 30, higher is better), and only the 2,100 who attended are in the data. People with hearing loss and people with poorer memory were less likely to attend. With social isolation as the proposed mediator, both models were adjusted for age and fitted to the same 2,100 people, and R prints the associations of hearing loss with the cognitive score below. The draft report says: "Hearing loss lowers cognition mainly by isolating people." Which revision suits these data?

> c(total = c_total, direct = c_direct, indirect = c_total - c_direct)
   total   direct indirect
    -2.4     -1.8     -0.6
> (c_total - c_direct) / c_total    # share of the total
[1] 0.25
Attendance is a collider affected by both hearing loss and cognition, and the bias comes from who is in the data, so adjusting for age or any covariate cannot remove it. The causal wording also goes beyond a single visit.
The revision uses associational wording, reads the printed share as about a quarter, and names the selection problem: attendance is a collider, and analysing attenders only can distort the estimates in a way that adding covariates cannot fix.
A negative indirect association shows its direction, not its size. The printed share is about a quarter of the total association, not most of it.
Fitting both models to the same people makes the decomposition valid but does not make it causal. Isolation and cognition were measured at the same visit, so temporal order cannot be established.
The correct revision uses associational wording, reads the share correctly and names the selection problem. R prints an indirect association of −0.6 points, 0.25 of the total of −2.4, so isolation statistically accounts for about a quarter of the association, not most of it ("mainly" in the draft and the third option are wrong). Attending the visit is affected by both hearing loss and cognition, so it is a collider, and analysing attenders only conditions on it; this selection bias comes from who is in the data, so adjusting for age or any other covariate cannot remove it (the first option). Fitting both models to the same people makes the decomposition valid, but it does not make the indirect association causal: isolation and cognition were measured at the same visit, so temporal order cannot be established (the last option). (Section 1, 1.1 Classifying a Third Variable with a DAG, the paragraph on colliders in how people come to be in the data; 2.1 Total, Direct and Indirect Effects; 7.1 Statistical Mediation in Cross-Sectional Data and Table 8.2; Objectives 1.1, 2.1 and 7.1)
● Complete the quiz to continue.
Section 2 of 4

Moderation: When an Association Differs Across Groups

⏱ Estimated time: 45 minutes
Lesson 8 · Section 2

Moderation: When an Association Differs Across Groups

A moderation question asks whether the association between an exposure and an outcome changes across the levels of a third variable.

Moderation

Three different questions about age

Confounding

Is support associated with loneliness once age is held constant? Age is added as a covariate.

Moderation

Does the support slope differ between age groups? An interaction term is added.

Mediation

Does a third variable lie on the pathway from support to the outcome? The association is split.

The interaction model

One model, two lines

Moderation by age group
\[ \begin{aligned} \text{loneliness} = {} & {\color{#6D28D9}{\beta_0}} + {\color{#1D4ED8}{\beta_1}}\,\text{support} + {\color{#C2410C}{\beta_2}}\,\text{older} \\ & + {\color{#CC0033}{\beta_3}}\,(\text{support} \times \text{older}) \end{aligned} \]
β1 support slope, under 50 β2 group difference at support = 0 β3 difference in slopes (older minus younger)

The support slope is β1 for adults under 50 and β1 + β3 for adults aged 50 and over.

CSCS result

A steeper slope for adults aged 50 and over

Scatterplot of loneliness against social support with two fitted lines: under 50 with slope minus 0.50 and 50 and over with a steeper slope of minus 0.81.
The interaction coefficient is −0.31 (p < 0.001), and the support slope is −0.50 under 50 and −0.81 at 50 and over.
Centring

Centring moves zero to the middle of the data

CoefficientUncentredCentredWhat the centred value describes
Support−0.1685−0.5776Support slope at the mean age (39.5 years)
Age0.05750.0065Age slope at the mean support score (4.93)
Support × age−0.0103−0.0103Change in the support slope per year of age
Simple slopes

The support slope at ages 30, 50 and 70

Three predicted lines of loneliness against support for ages 30, 50 and 70, with slopes of minus 0.48, minus 0.69 and minus 0.89.
The simple slope equals −0.5776 + (−0.0103) × (age − 39.54).
Two scales

Additive and multiplicative interaction

GroupRisk, unexposedRisk, exposedRisk differenceRisk ratio
Group A10%20%10 points2.0
Group B20%40%20 points2.0

The risk ratios are equal (no multiplicative interaction), and the risk differences differ (additive interaction).

Carry forward

What to take into the next section

  • Moderation is tested with an interaction term, and adding a covariate does not test it.
  • With an interaction in the model, main effects describe slopes at zero on the other variable, so centring and simple slopes make them readable.
  • Moderation is reported with the interaction coefficient, the simple slopes and a plot of one line per group.

Overview

The second question from the community connector program asks whether the association between social support and loneliness is the same for younger and older adults. This is a question of moderation. A moderator is a variable across whose levels the association between an exposure and an outcome differs in size or direction. Epidemiologists usually call the same idea effect modification, a term met in Section 1, and psychologists usually call it moderation. In a regression, moderation is examined by adding an interaction term, the product of the exposure and the moderator. This section treats moderation as a research question. It first separates moderation from confounding and mediation, then fits an interaction model to the CSCS data with age in two groups, explains how the other coefficients are read when an interaction is present and why centring a continuous moderator helps, and obtains simple slopes at chosen ages. It closes with the scale on which an interaction is measured and the reporting of a moderation result.

Learning Objectives

  • 3.1 Distinguish a moderation question from a confounding question and from a mediation question, and explain why adjusting for a variable does not test whether it modifies an association.
  • 3.2 Fit and interpret a linear regression with an interaction between a continuous exposure and a binary moderator: the interaction coefficient, its p-value and the slope of the exposure in each group.
  • 3.3 Explain what the main effects mean when an interaction is present, and why centring a continuous moderator helps.
  • 3.4 Obtain in R, plot and interpret simple slopes at chosen values of a moderator that are well represented in the data.
  • 3.5 Explain the difference between interaction on the additive and multiplicative scales, and why the additive scale usually matters more for public health decisions.
  • 7.2 Report a moderation result in words, with the slope in each group and a figure, without causal overstatement.

3.1 Moderation as a Research Question

Moderation asks for whom or under what conditions an association is stronger or weaker. Mediation, the topic of Section 3, asks why an association exists. A third question, confounding, asks whether an association remains once a common cause is held constant. The three can involve the same variables, but they are different questions with different models. Table 8.3 poses one question of each type about age in the running case and shows the model that answers each one in R.

Table 8.3. Three questions about age in the running case, with the type of question, the model in R and what the model gives.

Question about ageTypeModel in RWhat the model gives
Is support associated with loneliness once age is held constant?Confoundinglm(loneliness ~ support + age_group)One support slope for everyone, adjusted for age.
Is the support slope different for adults aged 50 and over?Moderationlm(loneliness ~ support * age_group)A support slope for each age group and a test of the difference.
Does a third variable carry part of the association from support to depressive symptoms?MediationSeveral models (Section 3)A direct part and an indirect part.

The models in the first two rows of Table 8.3 both contain age, and they differ by one term. That single term is the difference between adjusting for age and testing whether age modifies the association.

Adjusting for a Variable Does Not Test Whether It Modifies an Association

Adding age to a model as a covariate adjusts the support coefficient for age. By this we mean that the model compares people of the same age, so that age differences cannot masquerade as a support association. The model still estimates a single slope for support, however, which is assumed to be the same at every age, and it contains no test of whether the slope differs. In other words, adjustment answers the question "is there an association once age is held constant?", not the question "is the association the same size at every age?". Testing moderation requires a term that allows the slope to change with age, which is the interaction term. A variable can be a confounder, a moderator, both or neither, and each role is checked with a different model.

A moderation question therefore needs a model in which the slope of support can change with age, which is the model that the next subsection writes, fits and interprets.

3.2 Fitting and Interpreting an Interaction Model

3.2.1 The Interaction Model

For the running case, the moderator is an indicator called older, equal to 1 for adults aged 50 and over and 0 for adults under 50 (the reference group). The interaction model adds the product of support and the indicator to a model that already contains both. The product term is what allows the slope to differ between groups. For adults under 50 the indicator is 0, so the product is also 0 and the term drops out; for adults aged 50 and over the indicator is 1, so the product equals the support score and its coefficient adds to the support slope in that group only. Equation 8.2 writes the model with four coefficients, and the explanation under it shows how the model reduces to one line for each age group.

Linear regression with an interaction term
\[ \begin{aligned} \text{loneliness} = {} & {\color{#6D28D9}{\beta_0}} + {\color{#1D4ED8}{\beta_1}}\,\text{support} + {\color{#C2410C}{\beta_2}}\,\text{older} \\ & + {\color{#CC0033}{\beta_3}}\,(\text{support} \times \text{older}) + \varepsilon \end{aligned} \]Eq 8.2
For adults under 50 (older = 0), the model reduces to β0 + β1 × support. For adults aged 50 and over (older = 1), it becomes (β0 + β2) + (β1 + β3) × support. The interaction coefficient β3 is therefore the difference between the two slopes.

In R, support * age_group is shorthand for support + age_group + support:age_group, so the main effects are included automatically. Table 8.4 gives the name of each coefficient in the R output and its meaning.

Table 8.4. The four coefficients of Equation 8.2, their names in the R output and their meaning.

CoefficientName in R outputMeaning
β0(Intercept)Predicted loneliness for an adult under 50 with a support score of 0.
β1supportSlope of support among adults under 50 (the reference group) only.
β2age_group50 and overDifference in predicted loneliness between the age groups at a support score of 0.
β3support:age_group50 and overDifference between the support slope at 50 and over and the support slope under 50.

The key line of Table 8.4 is the last one: the interaction coefficient β3 is the difference between the two slopes. Because it is a difference, its p-value tests whether the slopes differ: a coefficient close to 0 would mean that support is associated with loneliness to the same degree in both groups, and a coefficient far from 0 means that it is not. It also follows that β3 is not itself the slope of either group. The slope in the reference group is β1, and the slope in the other group is β1 + β3, the reference slope plus the difference.

3.2.2 Moderation by Age Group in the CSCS

Of the 3,110 people in the CSCS sample, 2,275 are under 50 and 835 are aged 50 and over. A model that only adjusts for age group, lm(loneliness ~ support + age_group), fits one support slope for everyone (−0.62), so it says nothing about whether the slope differs by age. The interaction model, lm(loneliness ~ support * age_group), gives a support coefficient of −0.495, which is the slope among adults under 50 only, and an interaction coefficient of −0.312 (p = 2.1 × 10−9). R does not print the slope among adults aged 50 and over as a coefficient; the line coef(model_int)["support"] + coef(model_int)["support:age_group50 and over"] in Activity 8.2 obtains it and prints −0.808, about −0.81. Among adults under 50, a support score one point higher is associated with a loneliness score about 0.50 points lower; among adults aged 50 and over, the association is stronger, about 0.81 points lower per point of support. The negative interaction means a steeper slope in the older group, so the association is stronger there, not weaker. An anova() comparison of the models without and with the interaction gives F = 36.1 on 1 degree of freedom and the same p-value as the t test of the interaction coefficient, because the two models differ by one term. Together the three predictors explain about 18% of the variation in loneliness (R-squared 0.177).

Figure 8.4 makes the interaction visible. It plots loneliness against support with one fitted line for each age group, and the line for adults aged 50 and over is the steeper of the two.

Scatterplot of UCLA loneliness score against social support, with jittered grey points and two fitted lines. The blue line for adults under 50 falls from about 7.4 at support 1 to about 4.5 at support 7. The red line for adults aged 50 and over is steeper, falling from about 9 to about 4. The lines cross near a support score of 6.
Figure 8.4. One fitted line for each age group, drawn by the plotting code in Activity 8.2. The line for adults aged 50 and over is steeper (slope −0.81) than the line for adults under 50 (slope −0.50), and the two lines cross near a support score of 5.9.

Click each of the four cards below to review the terms used in reading this output: the interaction coefficient, the simple slope, the main effect and the comparison of models.

Interaction coefficientClick to explore
Simple slopeClick to explore
Main effectClick to explore
Comparing modelsClick to explore

The main-effect card makes a point that is easy to miss, and it is the subject of the next subsection: once an interaction is in the model, the other coefficients no longer mean what they mean in a model without one.

3.3 Main Effects and Centring

3.3.1 Reading the Main Effects When an Interaction Is Present

Once an interaction term is in the model, each main effect describes a slope or a difference at the zero point of the other variable. By this we mean that a main effect becomes a conditional effect: it describes one variable only at the point where the other variable in the interaction equals zero, and not an average over everyone. This happens because, when the other variable is not zero, the interaction term also contributes and changes the slope. The support coefficient (−0.50) is the support slope for adults under 50, and it applies to no one else. The age_group50 and over coefficient (1.83) is the difference between the age groups at a support score of 0. The support scale runs from 1 to 7, so a score of 0 is impossible, and this coefficient has no practical meaning on its own. Because of the interaction, the gap between the age groups changes with support, shrinking by the interaction coefficient for each additional point of support. The fitted lines in Figure 8.4 show this: adults aged 50 and over are predicted to be about 1.5 points lonelier at a support score of 1, the gap is small by a score of 5, and the lines cross near a score of 5.9. Reporting the 1.83 as "the effect of being older" would misread the model, which is one of the most common errors with interaction terms.

3.3.2 Centring a Continuous Moderator

Splitting age at 50 is easy to explain, but it treats a 49-year-old and a 20-year-old as alike, and it discards information. Age can instead enter the model as a continuous moderator, in lm(loneliness ~ support * age). The difficulty is that the main effects still describe slopes at zero on the other variable. The support coefficient becomes the slope of support for a person aged 0, and the age coefficient becomes the slope of age for a person with a support score of 0. Neither person exists in the data.

Centring solves this. A variable is centred by subtracting a chosen value from every observation, most often the mean, so that 0 on the centred variable means "average" (Aiken and West, 1991). By this we mean that the variable keeps exactly the same spread and the same differences between people; only the label attached to each value moves. For example, if age is centred at 40, a 40-year-old has a centred age of 0, a 50-year-old has 10 and a 30-year-old has −10. Because the main effects describe slopes where the other variable equals 0, moving the zero point to a typical value turns them into slopes for a typical person. In the CSCS sample the mean age is 39.54 years and the mean support score is 4.93. After centring, the support_c coefficient is the support slope at the mean age, and the age_c coefficient is the age slope at the mean support score. Centring at another meaningful value, such as age 65, is also legitimate, as long as the report says which value was used. Table 8.5 places the coefficients of the uncentred and centred models, both fitted in Activity 8.2, side by side and gives the meaning of each one in the centred model.

Table 8.5. Coefficients of the uncentred and centred interaction models of loneliness on support and age, from Activity 8.2.

CoefficientUncentred modelCentred modelMeaning in the centred model
Intercept6.14185.5660Predicted loneliness at the mean age and mean support
Support−0.1685−0.5776Support slope at the mean age of 39.5 years
Age0.05750.0065Age slope (per year) at the mean support score of 4.93
Support × age−0.0103 (t = −7.00)−0.0103 (t = −7.00)Change in the support slope for each additional year of age

The interaction coefficient and its t value are identical in the two models. Centring changes the zero point of each variable, and therefore what the main effects describe, but it leaves the interaction, the fitted values and the overall fit of the model unchanged. This is because the two models are the same set of fitted lines written in different units: the interaction says how much the support slope changes per year of age, and a year of age is still a year whether age is counted from birth or from the mean. The main effects change only because they are now read at a different point on each scale. Centring also lowers the correlation between a main effect and its product term, but the support slope at any given age has the same estimate and standard error in both models, and the test of the interaction is unchanged. An uncentred and a centred model with different main effects but an identical interaction are exactly what should be expected.

With age continuous there is a different support slope at every age, and the centred coefficients are the starting point for calculating them.

3.4 Simple Slopes at Chosen Values of the Moderator

A simple slope is the slope of the exposure at one chosen value of the moderator. By this we mean the answer to a question of the form "among people aged 70, how much lower is loneliness for each extra point of support?" A single interaction coefficient tells us that the slope changes with age, but it does not say how strong the association is for any particular group, and simple slopes fill that gap by turning the model into statements about specific people. With a binary moderator the simple slopes are the slopes in each group, −0.50 and −0.81 in 3.2. With a continuous moderator the simple slope at a chosen age comes straight from the centred coefficients: Equation 8.3 gives the simple slope at any age A, using the centred model in Table 8.5.

Simple slope of support at age A (centred model)
\[ \text{slope}(A) = {\color{#1D4ED8}{-0.5776}} + {\color{#CC0033}{(-0.0103)}} \times (A - 39.54) \]Eq 8.3
The slope at age A is the slope of support at the mean age, plus the interaction coefficient for each year above or below the mean. R does the calculation: the last part of Activity 8.2 computes the slopes in one line from the unrounded coefficients and prints −0.479 at age 30, −0.686 at age 50 and −0.893 at age 70. At age 70, for example, a support score one point higher is associated with a loneliness score about 0.89 points lower.

Interactive 8.2 applies Equation 8.3 to any age between 20 and 80. Move the slider and watch how the slope of support becomes steeper with age, and note where the ages fall relative to the 24 to 66 years that cover most participants.

📊 Interactive 8.2: Simple slope of support at a chosen age

At age 50, the simple slope of support is -0.69.

The bar shows the size of the slope. The calculation uses the centred CSCS model; most participants were aged between 24 and 66 (the 10th and 90th percentiles), so slopes outside that range rest on fewer people.

Figure 8.5 draws the predicted lines at ages 30, 50 and 70, the three ages whose simple slopes Activity 8.2 prints.

Three predicted lines of loneliness against social support for ages 30, 50 and 70. The age 70 line is steepest, falling from about 9.3 at support 1 to about 3.9 at support 7. The age 30 line is flattest, falling from about 7.4 to about 4.5. The lines cross near a support score of 5.6.
Figure 8.5. Predicted loneliness at ages 30, 50 and 70 from the centred model. The simple slopes are −0.48, −0.69 and −0.89. Older adults with low support are predicted to be lonelier than younger adults with low support, and predicted loneliness is similar across ages at high support.

Simple slopes should be computed at values of the moderator that are well represented in the data, because slopes at extreme values rest on few people. Common choices are the mean and one standard deviation above and below it, or meaningful values such as ages 30, 50 and 70. A plot with one line per chosen value, like Figure 8.5, is usually the clearest way to present a moderation result. As a check, the printed slopes should change steadily in the direction of the interaction coefficient, here becoming steeper at each older age.

Activity 8.2 brings 3.2, 3.3 and this subsection together. Run it along with the text: it creates the two age groups, fits and compares the models without and with the interaction, draws the plot in Figure 8.4, fits the uncentred and centred models with age in years and computes the simple slopes at ages 30, 50 and 70. Its questions ask you to interpret the interaction and the slopes, explain how centring changes the main effects, and check that the chosen ages are well represented.

R Activity 8.2: moderation by age group and by age in years

Text version of the activity: the code of the run-along script, its console output and notes on reading it.

github_url <- "https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"
load(url(github_url))                      # survey data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
med_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,
  depression = data$WELLNESS_phq_score,    # used in Section 3
  age        = data$DEMO_age)
med_data <- na.omit(med_data)              # the same people in every model
med_data$age_group <- NA
med_data$age_group[med_data$age < 50] <- "Under 50"
med_data$age_group[med_data$age >= 50] <- "50 and over"
med_data$age_group <- factor(med_data$age_group,
                             levels = c("Under 50", "50 and over"))
table(med_data$age_group)                  # "Under 50" is the reference
Console output
Under 50 50 and over 2275 835

This activity uses the same data and preparation as Section 1 and adds the moderator, so it can be run on its own. The depression score is kept so that the same 3,110 people are analysed in every model of the lesson. The age groups are made with the bracket recoding pattern from the data cleaning walkthrough. The table confirms 2,275 adults under 50 and 835 adults aged 50 and over, and setting levels in factor() makes "Under 50" the reference group.

model_main <- lm(loneliness ~ support + age_group, data = med_data)
coef(model_main)                           # one support slope for everyone
model_int <- lm(loneliness ~ support * age_group, data = med_data)
summary(model_int)
anova(model_main, model_int)               # does the interaction improve the model?
Console output
(Intercept) support age_group50 and over 8.5377220 -0.6179772 0.3078000 Call: lm(formula = loneliness ~ support * age_group, data = med_data) Residuals: Min 1Q Median 3Q Max -4.6054 -1.1045 -0.0618 1.0183 4.8955 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 7.92828 0.16529 47.967 < 2e-16 *** support -0.49548 0.03256 -15.216 < 2e-16 *** age_group50 and over 1.83149 0.26143 7.006 3.0e-12 *** support:age_group50 and over -0.31242 0.05200 -6.008 2.1e-09 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 1.565 on 3106 degrees of freedom Multiple R-squared: 0.1774, Adjusted R-squared: 0.1766 F-statistic: 223.3 on 3 and 3106 DF, p-value: < 2.2e-16 Analysis of Variance Table Model 1: loneliness ~ support + age_group Model 2: loneliness ~ support * age_group Res.Df RSS Df Sum of Sq F Pr(>F) 1 3107 7696.4 2 3106 7608.0 1 88.415 36.096 2.096e-09 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Reading the output. model_main adjusts for age group and fits one support slope for everyone (−0.618), so it contains no test of whether the slope differs by age. In model_int, support * age_group is shorthand for support + age_group + support:age_group. The support coefficient (−0.495) is the support slope among adults under 50 only. The interaction coefficient support:age_group50 and over (−0.312, p = 2.1 × 10−9) is the difference between the slopes. The age_group50 and over coefficient (1.83) compares the groups at a support score of 0, outside the 1 to 7 scale. Together, the three predictors explain about 18% of the variation in loneliness (R-squared 0.177). The anova() comparison tests whether adding the interaction improves the model: F = 36.1 on 1 degree of freedom (p = 2.1 × 10−9), the same p-value as the t test of the interaction coefficient, because the two models differ by one term (F is the square of that t value, −6.008).

coef(model_int)["support"]                                     # Under 50
coef(model_int)["support"] + coef(model_int)["support:age_group50 and over"]   # 50 and over
plot(jitter(med_data$support), jitter(med_data$loneliness),
     xlab = "Social support (1 to 7)", ylab = "UCLA loneliness score (3 to 9)",
     pch = 16, col = rgb(0, 0, 0, 0.10))
abline(lm(loneliness ~ support,
          data = med_data[med_data$age_group == "Under 50", ]),
       col = "steelblue", lwd = 3)
abline(lm(loneliness ~ support,
          data = med_data[med_data$age_group == "50 and over", ]),
       col = "firebrick", lwd = 3)
legend("topright", legend = c("Under 50", "50 and over"),
       col = c("steelblue", "firebrick"), lwd = 3)
Console output
support -0.4954754 support -0.807896
Scatterplot of UCLA loneliness score against social support, with jittered grey points and two fitted lines. The blue line for adults under 50 falls from about 7.4 at support 1 to about 4.5 at support 7; the steeper red line for adults aged 50 and over falls from about 9 to about 4.1. The lines cross near a support score of 5.9.

The simple slopes are −0.495 under 50 and −0.808 at 50 and over: the second line has R add the interaction coefficient (−0.312) to the under-50 slope, and R keeps the name support on the result because it is the first coefficient in the sum. The plotting code produces no console output: it draws the scatterplot with one fitted line per age group shown above and in Figure 8.4. jitter() adds a small random amount to each value so that people with the same scores do not hide behind one another.

med_data$age_c     <- med_data$age - mean(med_data$age)
med_data$support_c <- med_data$support - mean(med_data$support)
round(c(mean_age = mean(med_data$age), mean_support = mean(med_data$support)), 2)
model_raw <- lm(loneliness ~ support * age, data = med_data)       # uncentred
model_cen <- lm(loneliness ~ support_c * age_c, data = med_data)   # centred
round(summary(model_raw)$coefficients[, 1:3], 4)   # estimate, SE, t value
round(summary(model_cen)$coefficients[, 1:3], 4)
Console output
mean_age mean_support 39.54 4.93 Estimate Std. Error t value (Intercept) 6.1418 0.3527 17.4156 support -0.1685 0.0696 -2.4202 age 0.0575 0.0075 7.6817 support:age -0.0103 0.0015 -6.9994 Estimate Std. Error t value (Intercept) 5.5660 0.0281 198.3290 support_c -0.5776 0.0261 -22.0972 age_c 0.0065 0.0017 3.7367 support_c:age_c -0.0103 0.0015 -6.9994

Reading the output. The mean age is 39.54 years and the mean support score is 4.93, so 0 on age_c means 39.54 years and 0 on support_c means a support score of 4.93. Only the estimate, standard error and t value columns are printed, using [, 1:3], so that the tables fit on the screen. In the uncentred model, the support coefficient (−0.1685) is the support slope at age 0 and the age coefficient (0.0575) is the age slope at a support score of 0, both outside the data. In the centred model, the support_c coefficient (−0.5776) is the support slope at the mean age, and the age_c coefficient (0.0065) is the age slope at the mean support score. The interaction coefficient is −0.0103 with t = −7.00 in both models: each additional year of age makes the support slope about 0.01 more negative.

b <- coef(model_cen)
ages <- c(30, 50, 70)
slopes <- b["support_c"] + b["support_c:age_c"] * (ages - mean(med_data$age))
names(slopes) <- paste("age", ages)
round(slopes, 3)
Console output
age 30 age 50 age 70 -0.479 -0.686 -0.893

The simple slopes of support are −0.479 at age 30, −0.686 at age 50 and −0.893 at age 70. The slope becomes about 0.21 more negative with every 20 years of age, in the direction of the interaction coefficient (−0.0103 per year). Question 3 asks you to run quantile(med_data$age, c(0.10, 0.90)) and sum(med_data$age >= 70) to check that these ages are well represented in the data.

Files for this activity Data Code Answer key

R Reflect on what you just ran

Answer each question from your own output, as on the final exam: find the number, say what it means, judge the claim.

1. Does the association between social support and loneliness differ by age group? Interpret the interaction coefficient (−0.31) and its p-value, and interpret the two slopes (−0.50 for adults under 50 and −0.81 for adults aged 50 and over) in plain words. A colleague says: “model_main already adjusts for age group, so I have tested whether age modifies the association.” Respond.

Model answerYes: the interaction coefficient (−0.31) is the difference between the slopes in the two age groups, so the association is 0.31 points of loneliness per point of support stronger (steeper) among adults aged 50 and over. Its p-value (2.1 × 10−9) is far below 0.05, so the data show that the association differs by age group: age group modifies the association, and the anova() comparison gives the same p-value (F = 36.1, the square of t = −6.008) because the two models differ by one term. Among adults under 50, a support score one point higher is associated with a loneliness score about 0.50 points lower. Among adults aged 50 and over, the association is stronger: about 0.81 points lower per point of support (R prints −0.808, the under-50 slope plus the interaction coefficient). The colleague is wrong: model_main adjusts for age group but fits one common support slope (−0.62) for both groups, so it does not test whether the slope differs; moderation is tested with an interaction term, as in model_int, or by fitting the model separately in each age group.

2. Explain why the support coefficient is −0.1685 in model_raw and −0.5776 in model_cen. Which quantities are the same in both models? Using the same idea, what does the age_group50 and over coefficient (1.83) in model_int describe, and why is “being 50 or over raises loneliness by 1.83 points” a misreading?

Model answerWith an interaction in the model, each main effect is the slope of one variable when the other variable in the interaction equals 0. In the uncentred model, −0.1685 is the support slope for a person aged 0, who does not exist in the data. After centring, 0 on age_c is the mean age of 39.5 years, so −0.5776 is the support slope for a person of average age (and 0.0065 is the age slope at the mean support score of 4.93). Centring only moves the zero points, so the interaction coefficient (−0.0103), its t value (−7.00), the fitted values and the R-squared are the same in both models. In the same way, the age_group50 and over coefficient (1.83) is the difference between the age groups at a support score of 0, which lies outside the 1 to 7 scale. It is not the effect of being older: because of the interaction, the gap between the groups changes with support (in the plot, about 1.5 points at a support score of 1 and 0.27 at 5, with the lines crossing near 5.9), and “raises” is causal wording that one cross-sectional survey cannot support.

3. Run your own code: at the end of the script, type quantile(med_data$age, c(0.10, 0.90)) and sum(med_data$age >= 70) and run them. Write one or two sentences for a report that describe the simple slopes at ages 30, 50 and 70 in plain words. Why are these ages sensible choices here, and what is one caution about reading the slopes as changes with age?

Model answerYour output shows that the 10th and 90th percentiles of age are 24 and 66 years, and that 205 of the 3,110 people are aged 70 or over. The association between social support and loneliness was stronger at older ages: each additional point of support was associated with a loneliness score 0.48 points lower at age 30, 0.69 points lower at age 50 and 0.89 points lower at age 70 (interaction coefficient −0.010 per year of age, t = −7.00). These ages are sensible choices because simple slopes should be reported where the moderator is well represented: 30 and 50 lie inside the middle 80% of the sample (24 to 66 years), and 70 lies just above it but still rests on 205 people, whereas a slope at an age such as 90 would rest on almost no one. Because the survey is cross-sectional, these slopes compare different people of different ages at one time; they do not show how the association changes as a person grows older, and part of the difference may reflect the generation to which people belong.
Saved.

Every number used in 3.2 to 3.4 comes from this output: the interaction coefficient of −0.31 and the slopes of −0.50 and −0.81, the centred coefficients in Table 8.5 and the simple slopes of −0.48, −0.69 and −0.89. All of them compare slopes of a continuous outcome, which are differences, and the next subsection sets this additive scale beside the multiplicative scale of a logistic regression.

3.5 Additive and Multiplicative Scales

Whether an interaction exists depends on the scale on which the association is measured. By this we mean that "the association is the same in both groups" can be judged in two ways: by asking whether the exposure adds the same amount to the outcome in each group, or by asking whether it multiplies the outcome by the same factor. These are different standards, and data that meet one need not meet the other. In a linear regression of a continuous outcome, the interaction compares slopes, which are differences, so it is an interaction on the additive scale. In a logistic regression, the interaction term compares odds ratios, so it is an interaction on the multiplicative scale. The same data can show an interaction on one scale and none on the other, as the hypothetical example in Table 8.6 shows.

Table 8.6. A hypothetical exposure with the same risk ratio in two groups and different risk differences.

GroupRisk without exposureRisk with exposureRisk differenceRisk ratio
Group A10%20%10 percentage points2.0
Group B20%40%20 percentage points2.0

The risk ratio is 2.0 in both groups, so there is no interaction on the multiplicative scale. The risk difference is twice as large in group B, so there is an interaction on the additive scale. For public health decisions the additive scale is often the more relevant one, because it shows in which group an intervention would prevent more cases. For example, removing the exposure in group B would prevent about 20 cases per 100 people, compared with about 10 per 100 in group A, even though the risk ratio is identical. A planner with limited resources would therefore reach more cases by starting with group B, a conclusion that the risk ratios alone would hide.

The two scales can even point in opposite directions. If the risk rose from 5% to 20% in one group (a risk difference of 15 points and a risk ratio of 4.0) and from 12% to 36% in another (a risk difference of 24 points and a risk ratio of 3.0), the association would be stronger in the second group on the additive scale and weaker on the multiplicative scale, and removing the exposure would prevent more cases in the second group. For binary outcomes, reports should present the association within each group, comparing the groups on both the risk difference and the risk ratio, and state which scale any interaction refers to (Knol and VanderWeele, 2012; VanderWeele and Knol, 2014). The outcomes in this lesson are continuous scores, so every interaction here is on the additive scale.

With the scale settled, the remaining step is to report the CSCS moderation result.

7.2 Reporting a Moderation Result

A moderation result is reported with the interaction coefficient and its confidence interval or p-value, the simple slopes, and a plot with one line per group or per chosen value of the moderator. The language describes associations. A suitable sentence for the CSCS result is: "The association between social support and loneliness differed by age group (interaction coefficient −0.31, p < 0.001). Each additional point of support was associated with a loneliness score 0.50 points lower among adults under 50 and 0.81 points lower among adults aged 50 and over." Refitting the model with "50 and over" as the reference group gives that group's slope with its own confidence interval, which can be added to the report. If the model includes covariates, the report names them, because each slope then compares people with the same values of those covariates.

Two cautions belong in the report. First, the slopes describe associations, so the sentence says that support was "associated with" lower loneliness, not that support lowered it. Second, when the moderator is age and the data come from one survey, the two slopes compare different people of different ages at a single time. They do not show how the association changes as a person grows older, which would need repeated measurements of the same people, and part of any difference between age groups may reflect the generations to which people belong.

The narrated walkthrough in the red card below offers a second route through the steps of Activity 8.2, with each line of code explained as it runs.

Learn to do this in R

Narrated R walkthrough: Mediation and Moderation

The Mediation and Moderation walkthrough runs the moderation code in this section line by line with narration, including the age groups, the anova() comparison, the simple slopes and the plot with one line per group. Its first half covers the mediation analysis in Section 3.

Open the Mediation and Moderation walkthrough

This section has shown that the association between social support and loneliness is stronger at older ages, whether age is split at 50 or treated as a continuous moderator, and it has set out how such a result is reported on a stated scale. Section 3 turns to the first question of the running case, whether loneliness carries part of the association between support and depressive symptoms. The key takeaways and knowledge check below review this material.

Key Takeaways

  • 3.1 Moderation, confounding and mediation can involve the same variables, but they ask different questions. Moderation asks for whom, or under what conditions, an association is stronger or weaker; confounding asks whether the association remains once a common cause is held constant; and mediation asks why the association exists. The common trap is to assume that adding a variable to the model tests whether it modifies the association: lm(loneliness ~ support + age_group) still fits one support slope for everyone, so it adjusts for age but cannot show whether the slope differs by age. Only the interaction model, lm(loneliness ~ support * age_group), allows a separate slope in each group and tests the difference. If a question describes a study that "controlled for" a variable and then concluded that the association was the same in every group, point out that the model never tested this.
  • 3.2 In a model with an interaction between a continuous exposure and a binary moderator, the interaction coefficient is the difference between the two groups' slopes. The support coefficient (β1) is the slope in the reference group only, and the slope in the other group is β1 + β3: in the CSCS, −0.50 among adults under 50 and −0.81 among adults aged 50 and over, the value R reports for the second group when you ask it for that slope. The p-value of the interaction coefficient (here p < 0.001) tests whether the slopes differ, and the anova() comparison of the models without and with the interaction gives the same p-value when they differ by one term. When you read the output, check which group is the reference, take the other group's slope from R (Activity 8.2 prints it with coef(model_int)["support"] + coef(model_int)["support:age_group50 and over"]), then interpret each slope as an association in the outcome's units, for example "among adults aged 50 and over, a support score one point higher is associated with a loneliness score about 0.81 points lower". A negative interaction here means the slope is steeper in the older group, so the association is stronger there, not weaker.
  • 3.3 Once an interaction is in the model, each main effect becomes a slope or a difference at zero on the other variable, not an average effect. The support coefficient is the support slope in the reference group only, and the age_group50 and over coefficient of 1.83 is the gap between the age groups at a support score of 0, which lies outside the 1 to 7 scale, so reporting it as "the effect of being older" is one of the most common errors with interaction terms. Centring fixes this by subtracting a chosen value, usually the mean, so that zero means "typical": after centring, the support coefficient is the slope at the mean age of 39.5 years and the age coefficient is the slope at the mean support score. Centring changes only what the intercept and main effects describe; the interaction coefficient, its t value, the fitted values and the overall fit stay the same. So if you are shown an uncentred and a centred model with different main effects but an identical interaction, that is exactly what you should expect.
  • 3.4 A simple slope is the slope of the exposure at one chosen value of the moderator. With a binary moderator the simple slopes are the slopes in each group; with a continuous moderator there is a different slope at every value, and R obtains it from the centred model as the exposure coefficient plus the interaction coefficient times the distance from the mean; one line of code in Activity 8.2 prints −0.48, −0.69 and −0.89 at ages 30, 50 and 70. Choose values that are well represented in the data, such as the mean and one standard deviation either side or meaningful ages such as 30, 50 and 70, because slopes at extreme values rest on few people. Present the result with a plot that has one fitted line per group or chosen value, which is usually the clearest way to show moderation. As a check, the slopes should change steadily in the direction of the interaction coefficient, here becoming about 0.21 more negative for every 20 years of age.
  • 3.5 Whether you find an interaction depends on the scale on which the association is measured. A linear regression of a continuous outcome compares slopes, which are differences, so its interaction is on the additive scale; an interaction term in a logistic regression compares odds ratios, so it is on the multiplicative scale. The same data can show an interaction on one scale and none on the other: in Table 8.6 the risk ratio is 2.0 in both groups, but the risk difference is 10 percentage points in one group and 20 in the other, and the two scales can even point in opposite directions. For public health decisions the additive scale usually matters more, because the risk difference shows in which group removing the exposure would prevent more cases. When output gives the risk difference and the risk ratio in each group, compare the groups on each measure, then state which scale any claim of interaction refers to.
  • 7.2 A good moderation report gives the interaction coefficient with its p-value or confidence interval, the slope of the exposure in each group (or at chosen values of the moderator) and a plot with one line per group. A sentence you can adapt is: "The association between social support and loneliness differed by age group (interaction coefficient −0.31, p < 0.001); each additional point of support was associated with a loneliness score 0.50 points lower among adults under 50 and 0.81 points lower among adults aged 50 and over." Use "associated with" rather than "lowered" or "raised", and name any covariates in the model, because each slope then compares people with the same covariate values. When the moderator is age and the data come from one survey, add that the slopes compare different people of different ages at one time and do not show how the association changes as a person grows older.
Knowledge check: this section

1. A survey of 1,500 adults asks whether the association between daily steps (in 1,000s) and systolic blood pressure differs between people with and without diabetes. A colleague fits lm(sbp ~ steps + diabetes) and says: "My model includes diabetes, so I have tested whether diabetes modifies the association." Which response is correct?

A variable added to a regression is adjusted for, not tested as a moderator. Moderation needs a term that lets the steps slope change with diabetes, the product term.
The diabetes coefficient tests a difference in blood pressure between people with and without diabetes, not a difference in the steps slope. A difference in slopes is tested by the interaction coefficient.
Adding diabetes as a covariate gives one steps slope assumed to be the same in both groups. The product term steps × diabetes lets the slope differ, and its coefficient is the difference between the two slopes.
Mediation asks how much of an association runs through a variable on the pathway. Whether an association differs in size between groups is moderation, tested with an interaction term or slopes estimated in each group.
The correct response is that adjusting is not testing, and an interaction term is needed. Adding diabetes as a covariate adjusts the steps slope for diabetes, but the model still estimates a single steps slope that is assumed to be the same with and without diabetes, so it contains no test of whether the slopes differ. Moderation needs a term that lets the slope change with diabetes, the product steps × diabetes (written steps * diabetes in R), whose coefficient is the difference between the two slopes. The p-value of the diabetes coefficient is the tempting wrong choice: it tests a difference in blood pressure between the groups, not a difference in slopes. Diabetes can be a confounder, a moderator, both or neither, and each role is checked with a different model. (Section 2, 3.1 Moderation as a Research Question, Table 8.3 and the callout "Adjusting for a Variable Does Not Test Whether It Modifies an Association"; Objective 3.1)

2. A cross-sectional survey of 2,000 adults regressed a stress score on weekly hours of exercise, sex and their interaction, with men as the reference group. Using the output below, in which the last lines give the exercise slope in each group, which two sentences report the result correctly?

TermEstimatep-value
(Intercept)24.00< 0.001
exercise−0.60< 0.001
sexWoman2.10< 0.001
exercise:sexWoman−0.400.003
> c(men = coef(m)[["exercise"]],
+   women = coef(m)[["exercise"]] + coef(m)[["exercise:sexWoman"]])
  men women
 -0.6  -1.0 
The report gives the interaction with its p-value, the slope in each group as R prints them, and associational wording suited to a cross-sectional survey. With men as reference, the exercise coefficient is the men's slope and the interaction is the difference between slopes.
The numbers match the output, but "lowered" and "reduced" are causal words that a cross-sectional survey cannot support. The result should be reported as an association.
The interaction's p-value is well below 0.05, so the data show that the slopes differ. This option also reads the interaction coefficient as the women's slope, when it is the difference between the women's and men's slopes.
The women's slope is the reference slope plus the interaction, as R prints it, not the reference slope minus the interaction. Subtracting reverses the direction of the difference between groups.
The correct report gives the interaction, both slopes and associational wording. With men as the reference group, the exercise coefficient (−0.60) is the slope among men, and the interaction coefficient (−0.40) is the difference between the slopes, women minus men. The slope among women, which R prints, is therefore −0.60 + (−0.40) = −1.00, and the interaction's p-value of 0.003 is below 0.05, so the data show that the slopes differ: the association is stronger among women. The second option has the right numbers but causal wording ("lowered", "reduced") that a cross-sectional survey cannot support; the third reads the interaction coefficient as the women's slope, and the fourth subtracts the interaction instead of adding it. (Section 2, 3.2 Fitting and Interpreting an Interaction Model, Eq 8.2 and Table 8.4; 7.2 Reporting a Moderation Result; Objectives 3.2 and 7.2)

3. In the same model, exercise ranges from 0 to 12 hours per week with a mean of 4 hours. The sexWoman coefficient is 2.10 and the exercise:sexWoman coefficient is −0.40. Refitting the model with exercise centred at its mean (exercise_c <- exercise - 4) gives the output below. A colleague writes that "women have stress scores 2.10 points higher than men". What is wrong with this reading?

> coef(m_c)[c("sexWoman", "exercise_c:sexWoman")]
           sexWoman exercise_c:sexWoman
                0.5                -0.4 
With an interaction in the model, a main effect is the difference when the other variable in the interaction equals zero. The sexWoman coefficient compares women and men who do no exercise, not on average.
The difference between the exercise slopes of women and men is the interaction coefficient. The sexWoman coefficient is a difference in stress scores, at zero hours of exercise.
No such division is part of reading the model. The sexWoman coefficient is already a difference in stress, but it applies only at zero hours of exercise; centring shows the difference at the mean.
The sexWoman coefficient applies where exercise equals zero, and the difference changes with exercise because of the interaction. Centring moves zero to the mean, so the centred model gives the difference for people at average exercise, with the interaction unchanged.
The correct answer is that 2.10 applies only at 0 hours of exercise. With an interaction in the model, a main effect is the slope or difference when the other variable in the interaction equals zero, so the sexWoman coefficient compares women and men at 0 hours. The difference changes with exercise, so the colleague's sentence overstates the typical difference. Centring moves the zero point to the mean of 4 hours, so in the centred model the sexWoman coefficient (0.5) is the difference between women and men at the mean, while the interaction (−0.4) is unchanged. The first option is the common error of reading a main effect as an average once an interaction is present. (Section 2, 3.3 Main Effects and Centring, 3.3.1 and 3.3.2, and Table 8.5; Objective 3.3)

4. Loneliness is regressed on support with age as a continuous moderator, after centring age at its mean of 45 years and support at its mean. The support_c coefficient is −0.50 and the support_c:age_c coefficient is −0.010 per year. Most participants are aged 25 to 70. R prints the simple slopes of support at three ages. Which statement is correct?

> slopes <- b["support_c"] + b["support_c:age_c"] * (c(45, 65, 95) - 45)
> names(slopes) <- paste("age", c(45, 65, 95))
> round(slopes, 2)
age 45 age 65 age 95
  -0.5   -0.7   -1.0 
After centring, zero on age_c means the mean age of 45, so the support_c coefficient is the support slope at age 45, not at age 0. Centring does not need to be undone, because it only moves the zero point.
Centring makes the support_c coefficient the slope at the mean age, and the simple slope at another age adds the interaction scaled by the distance from that mean. Centring changes what the main effect describes but not the interaction or fitted values.
With age centred, the interaction is scaled by the distance from the mean age, not by age itself. Centring also leaves the interaction coefficient, its t value and the fitted values unchanged.
Simple slopes are reported at values within the range where most people lie. An age of 95 is outside the 25 to 70 range, so a slope there rests on few people.
The correct statement gives −0.50 at age 45 and −0.70 at age 65. After centring, zero on age_c means the mean age of 45, so the support_c coefficient is the support slope for a person aged 45. The code adds the interaction times the distance from the mean age to that coefficient, so at age 65 it gives −0.50 + (−0.010) × (65 − 45) = −0.70. Centring moves the zero point, so it changes what the main effects describe, but the interaction coefficient, its t value, the fitted values and the R-squared stay the same. The third option forgets that the slope depends on the distance from the mean age, and the fourth reports a slope at an age outside the 25 to 70 range where most people lie, where the estimate rests on few people. (Section 2, 3.3.2 Centring a Continuous Moderator and Table 8.5; 3.4 Simple Slopes at Chosen Values of the Moderator, Eq 8.3, Interactive 8.2 and Activity 8.2; Objectives 3.3 and 3.4)

5. During a heat wave, the risk of an emergency visit for heat illness was compared between people with and without air conditioning at home, in two age groups (table below), and R computed the risk difference and the risk ratio for having no air conditioning in each group. On which scale is the association stronger among adults aged 65 and over, and what does that mean for deciding where to provide air conditioning?

Age groupRisk with air conditioningRisk without air conditioning
Under 652%6%
65 and over10%20%
> heat$risk_diff  <- heat$risk_no_ac - heat$risk_ac
> heat$risk_ratio <- heat$risk_no_ac / heat$risk_ac
> heat
    age_group risk_ac risk_no_ac risk_diff risk_ratio
1    Under 65    0.02       0.06      0.04          3
2 65 and over    0.10       0.20      0.10          2
The two scales point in opposite directions. The risk ratio is larger under 65, but the risk difference is larger at 65 and over, so judging by the risk ratio alone misses where more visits occur.
Risk being higher without air conditioning in both groups does not rule out interaction. Interaction is a difference in the size of the association between groups, and here the size differs on both scales, in opposite directions.
The risk difference is larger in older adults while the risk ratio is smaller, so the scales disagree. The additive scale shows where an intervention would prevent more cases, here among adults aged 65 and over, if the association were causal.
The risk ratio is smaller, not larger, at 65 and over. The interaction appears on both scales, pointing in opposite directions, and the additive one is larger among older adults.
The correct answer is that the association is stronger at 65 and over on the additive scale only. Read both measures from the R output, where the lack of air conditioning is the exposure. Under 65, the risk difference is 0.04 (4 percentage points) and the risk ratio is 3.0. At 65 and over, the risk difference is 0.10 (10 points) and the risk ratio is 2.0. The two scales point in opposite directions: the association is stronger in the older group on the additive scale and weaker on the multiplicative scale. The additive scale is the one that shows where an intervention would prevent more cases (about 10 visits per 100 older adults against 4 per 100 younger adults, if the association were causal). The first option is the tempting error of judging by the risk ratio alone. (Section 2, 3.5 Additive and Multiplicative Scales, Table 8.6 and the example in which the scales point in opposite directions; Objective 3.5)

6. A survey of 1,200 family carers fitted lm(distress ~ care10 * employed + age + female), where distress is the K6 score (0 to 24, higher means more distress), care10 is hours of care per week divided by 10, and carers not in paid work are the reference group. Using the output below, which statement is correct?

> round(summary(m)$coefficients[c("care10", "employedYes", "care10:employedYes"), ], 4)
                   Estimate Std. Error t value Pr(>|t|)
care10                  0.6       0.15     4.0   0.0001
employedYes            -1.2       0.40    -3.0   0.0028
care10:employedYes      0.5       0.20     2.5   0.0126
> c(not_employed = coef(m)[["care10"]],
+   employed = coef(m)[["care10"]] + coef(m)[["care10:employedYes"]])
not_employed     employed
         0.6          1.1 
The employedYes coefficient compares the groups at care10 = 0, that is, at no hours of care. Because of the interaction, the difference between employed and other carers changes with hours of care.
The employedYes coefficient compares the groups at no hours of care and does not test moderation. Whether employment modifies the association is tested by the interaction term, which cannot be ignored.
The care10 coefficient is the slope for carers not in paid work, R prints the slope for employed carers, and the interaction is the difference, which is significant. A linear model compares slopes, which are differences, so the interaction is on the additive scale.
A linear regression compares slopes, which are differences, so its interaction is on the additive scale. The slope among employed carers is the reference slope plus the interaction, not their product.
The correct statement reads the two slopes, the interaction and its scale. With carers not in paid work as the reference group, the care10 coefficient (0.6) is their slope, and the slope among carers in paid work, which R prints, is 1.1 K6 points per 10 hours of care, holding age and sex constant. The interaction coefficient (0.5) is the difference between the two slopes, and its p-value (0.0126) is below 0.05, so the association is stronger among carers in paid work. A linear regression compares slopes, which are differences, so the interaction is on the additive scale. The employedYes coefficient compares the groups at care10 = 0, that is, at no hours of care, so it is neither an overall difference (the first option) nor a test of moderation (the second). (Section 2, 3.2 Fitting and Interpreting an Interaction Model and Table 8.4; 3.3.1 Reading the Main Effects When an Interaction Is Present; 3.5 Additive and Multiplicative Scales; Objectives 3.2, 3.3 and 3.5)
● Complete the quiz to continue.
Section 3 of 4

Mediation: Direct and Indirect Effects

⏱ Estimated time: 50 minutes
Lesson 8 · Section 3

Mediation: Direct and Indirect Effects

The association between support and depressive symptoms is split into a part that runs through loneliness and a part that does not.

Three regressions

Estimating the paths one at a time

Model in RPathEstimate (95% CI)
lm(depression ~ support)c, total−0.560 (−0.608 to −0.511)
lm(loneliness ~ support)a−0.626 (−0.676 to −0.576)
lm(depression ~ support + loneliness)b0.366 (0.334 to 0.397)
c′, direct−0.331 (−0.380 to −0.282)
Indirect effect

Two methods, one answer

Product of coefficients and difference method
\[ \begin{gathered} {\color{#CC0033}{a \times b}} = (-0.626)(0.366) = -0.229 \\ {\color{#0B7B6B}{c}} - {\color{#1D4ED8}{c'}} = -0.560 - (-0.331) = -0.229 \end{gathered} \]
a × b product of coefficients c − c′ difference method
41%
of the total association statistically accounted for by loneliness (0.229 ÷ 0.560)
Baron and Kenny

Why the causal steps are no longer recommended

The four steps

X predicts Y; X predicts M; M predicts Y with X held constant; the X coefficient shrinks.

The problems

The steps never test a × b, they have low power, they miss inconsistent mediation, and their full and partial labels depend on sample size.

mediate()

Bootstrap estimates of the effects

QuantityEstimate95% bootstrap CI
ACME (indirect)−0.229−0.256 to −0.201
ADE (direct)−0.331−0.386 to −0.279
Total effect−0.560−0.618 to −0.509
Proportion mediated0.410.36 to 0.46
Caution and sensitivity

Proportion mediated and the sensitivity parameter

Sensitivity plot of the average mediation effect against the sensitivity parameter rho. The indirect effect is minus 0.23 at rho of zero and crosses zero at rho of about 0.4.
The indirect effect would reach zero if the residual correlation (ρ) were about 0.4.
Reporting

Reporting without causal overstatement

  • The report states the DAG, the covariates in each model and the assumptions a causal reading would need.
  • It gives the indirect, direct and total effects with bootstrap confidence intervals and the number of resamples.
  • It reports the sensitivity analysis and the limits of a cross-sectional design.
Loneliness statistically accounted for about 41% of the association between social support and depressive symptoms (indirect association −0.23, 95% CI −0.26 to −0.20).Suitable wording for the CSCS result
Carry forward

What to take into the next section

  • The indirect effect is a × b, which equals c − c′ in linear models fitted to the same people.
  • The indirect effect is tested directly with a bootstrap confidence interval.
  • A cross-sectional mediation result is reported as a statistical decomposition, with a sensitivity analysis.

Overview

Section 1 defined the total, direct and indirect effects and the conditions under which an indirect effect can be read causally. This section estimates them for the program's first question: is social support associated with fewer depressive symptoms partly because people with more support are less lonely? The analysis follows the history of the method. It first estimates each path with an ordinary linear regression and calculates the indirect effect in two ways. It then explains why the classic four-step approach to testing mediation has been replaced, estimates the indirect effect with a bootstrap confidence interval using the mediation package (Tingley et al., 2014), asks how much unmeasured confounding it could withstand, and ends with the reporting of a mediation analysis.

Learning Objectives

  • 4.1 Fit the three regressions that give paths a, b, c and c′, and interpret each path.
  • 4.2 Obtain in R and interpret the indirect effect from the product-of-coefficients and difference methods, and explain when the two agree.
  • 4.3 Explain the limits of the Baron and Kenny causal steps as a test of mediation, including why the labels "full" and "partial" mediation depend mainly on sample size.
  • 4.4 Estimate the indirect, direct and total effects with bootstrap confidence intervals using mediate(), explain why the bootstrap is used for the indirect effect, and interpret the proportion mediated with caution.
  • 5.1 Run and interpret a sensitivity analysis for unmeasured mediator-outcome confounding, and judge whether the indirect association is robust or fragile.
  • 7.3 Report a mediation analysis with its main elements (the DAG, the covariates, the effects with bootstrap intervals, the sensitivity analysis and the limits of the design) without causal overstatement.

4.1 Three Regressions, Four Paths

The recall below returns to the preview of mediation in Lesson 1 and its output, and its retrieval question asks about the quantity that mediate() reports.

Recall: Lesson 1, Section 1 (From DAG to Regression: A Mediation Example)

Lesson 1, Section 1 previewed mediation with simulated data in which education raises income and income improves health, with a direct path from education to health. It ran the three Baron and Kenny regressions and then the mediate() function, which reported an average causal mediation effect (ACME) of 0.30 (95% CI 0.24 to 0.35) and an average direct effect (ADE) of 0.35. That preview assumed the regression and counterfactual reasoning behind these numbers, and this section supplies it: each path comes from a linear regression of the kind fitted in Lesson 3, and the ACME and ADE rest on the counterfactual definitions given in Section 1.

Retrieval question. What does the ACME reported by mediate() estimate?

AnswerThe ACME is the indirect effect: the average change in the outcome that would follow if the mediator shifted from the value it would take at one level of the exposure to the value it would take at another, with the exposure itself held fixed. In a linear model without interactions it equals a × b. In cross-sectional data it is a statistical quantity despite its name.

With support as the exposure (X), loneliness as the mediator (M) and depressive symptoms as the outcome (Y), three linear regressions give every path in the mediation diagram. The total-effect model regresses the outcome on the exposure and gives path c. The mediator model regresses the mediator on the exposure and gives path a. The outcome model is the one that needs most thought, because it does two jobs at once. Putting both the exposure and the mediator into the same regression means that each coefficient is read with the other variable held constant. In this way path b describes the association between loneliness and depressive symptoms among people with the same level of support, and the exposure coefficient in the same model, c′, describes the association of support with depressive symptoms among people with the same level of loneliness. Holding support constant matters for path b because support is related to both loneliness and depressive symptoms; without it, b would partly reflect the association of support with the outcome rather than that of loneliness. Table 8.7 lists the three models, the R code for each, the coefficient that is used from it and the path that the coefficient estimates.

Table 8.7. The three regressions of a simple mediation analysis and the paths they estimate.

ModelR codeCoefficient usedPath
Total-effect modellm(depression ~ support)supportc (total effect)
Mediator modellm(loneliness ~ support)supporta
Outcome modellm(depression ~ support + loneliness)loneliness and supportb and c′ (direct effect)

A common slip when reading output is to take a coefficient from the wrong model, so it helps to match each path to its model before interpreting it. The models in this lesson have no covariates, so that the numbers match the narrated walkthrough. In a manuscript, the confounders identified in the DAG (for example age, gender and income) would be added to the mediator model and to the outcome model, so that paths a and b are adjusted for the common causes of the exposure and mediator and of the mediator and outcome, and each path would be described as adjusted for them.

Fitted to the 3,110 CSCS participants, the three models give a total effect of c = −0.560: each point of support is associated with a PHQ-2 score 0.560 points lower. Path a is −0.626: each point of support is associated with a loneliness score 0.626 points lower. Path b is 0.366: among people with the same support score, each point of loneliness is associated with a PHQ-2 score 0.366 points higher. The direct effect is c′ = −0.331: among people with the same loneliness score, each point of support is associated with a PHQ-2 score 0.331 points lower. Figure 8.6 places these estimates, which Activity 8.3 reproduces, on the mediation diagram of Figure 8.2.

Loneliness (3 to 9) Social support (1 to 7) Depressivesymptoms (0 to 6) a = −0.626 b = 0.366 c′ = −0.331 Total effect c = −0.560 · Indirect effect a × b = −0.229
Figure 8.6. The mediation model with the estimates from the three regressions (n = 3,110). The coefficients are unstandardized: each is the change in the outcome of its arrow for a one-point difference in the variable at the start of the arrow.

The direct effect (−0.331) is smaller in size than the total effect (−0.560), because part of the total runs through loneliness. The next subsection calculates that part.

4.2 Product-of-Coefficients and Difference Methods

The indirect effect can be calculated in two ways. The product-of-coefficients method multiplies path a by path b. The difference method subtracts the direct effect from the total effect. Equation 8.4 applies both methods to the CSCS estimates.

Two ways to compute the indirect effect
\[ \text{indirect effect} = {\color{#CC0033}{a \times b}} = {\color{#0B7B6B}{c}} - {\color{#1D4ED8}{c'}} \]Eq 8.4
The product of paths a and b and the difference between the total effect c and the direct effect c′ give the same indirect effect in linear models fitted to the same people. Activity 8.3 obtains both in R, with a * b and c_total - c_direct, and each prints −0.2289: about 0.23 fewer PHQ-2 points per point of support through loneliness.

The product-of-coefficients method has an intuitive reading. A support score one point higher goes with a loneliness score 0.626 points lower (path a), and each point of loneliness goes with 0.366 more PHQ-2 points among people with the same support (path b), so the pathway through loneliness combines the two, and the product that R prints, −0.229, corresponds to about 0.23 fewer PHQ-2 points per point of support. The signs can be read the same way: a negative a times a positive b gives a negative indirect effect, meaning that more support goes with less loneliness, which goes with fewer symptoms. The two methods agree exactly only when the mediator and outcome models are linear regressions fitted to the same people, so two printed values that agree also confirm that the models used the same people. When the outcome is binary and modelled with logistic regression, c − c′ and a × b can differ. The reason is a property of odds ratios called non-collapsibility. By this we mean that adding any variable that predicts the outcome to a logistic model tends to move the exposure coefficient further from zero, even when that variable is not a confounder at all. As a result, the change from c to c′ in a logistic model mixes two things, the part of the association carried by the mediator and the shift caused simply by adding another predictor, and the difference method can no longer separate them. The counterfactual approach used by mediate() handles such models consistently (Imai, Keele and Tingley, 2010; VanderWeele, 2015).

Figure 8.7 shows the result of the decomposition as two bars, with the total association above and its direct and indirect parts below.

Total c = −0.560 Split direct c′ = −0.331 indirect −0.229 41% of the total 59% of the total
Figure 8.7. The total association between support and depressive symptoms (−0.560 PHQ-2 points per point of support) split into a direct part (−0.331) and an indirect part through loneliness (−0.229). Bar lengths are proportional to the size of each association.

The product a × b is the quantity of interest in a mediation analysis. The older causal steps, which the next subsection describes, never test this product.

4.3 The Limits of the Baron and Kenny Causal Steps

For about two decades, most published mediation analyses followed the causal steps of Baron and Kenny (1986). Mediation was claimed when four conditions were met: the exposure predicted the outcome (path c), the exposure predicted the mediator (path a), the mediator predicted the outcome with the exposure held constant (path b), and the exposure coefficient shrank when the mediator was added (c′ smaller than c). If c′ fell to zero, the result was called full mediation, and otherwise partial mediation. The steps are still described in many textbooks, and students will meet them in published papers. Methodologists no longer recommend them as a test of mediation (MacKinnon et al., 2002; Hayes, 2009; Zhao, Lynch and Chen, 2010), for five reasons: they never test the indirect effect itself, they have low statistical power, they rule out inconsistent mediation, their "full" and "partial" labels depend mainly on sample size, and they leave the causal assumptions implicit. Expand each of the five panels of the accordion below for the reasoning behind each limitation.

The indirect effect is never tested

The quantity of interest is a × b, yet the steps test a and b separately and never test their product or give it a confidence interval. Separate significance tests are a poor guide to whether the product differs from zero. For example, a and b can each fall just short of significance while their product is clearly different from zero, or the reverse can happen. In addition, a pair of p-values gives no estimate of how large the indirect effect is or how precisely it is known, which is the information a reader actually needs.

Low statistical power

Requiring every step to be statistically significant makes the approach less powerful than a direct test of the indirect effect. Each additional hurdle is another chance for a real pathway to be rejected by chance, and the requirement of a significant total effect is often the hardest hurdle of all, because the total effect can be smaller and less precisely estimated than the indirect effect. As a result, real indirect effects are often missed in samples of ordinary size (Fritz and MacKinnon, 2007).

Inconsistent mediation is ruled out

The first step requires a significant total effect. When the direct and indirect effects have opposite signs, they can cancel out, so that the total effect is close to zero even though a real indirect effect exists. This pattern is called inconsistent mediation, or suppression, and the first step would stop the analysis before it was found. For example, an exercise program might reduce stress directly but also add a new time commitment that raises stress through a busier schedule; if the two pathways were similar in size, the program would show little overall association with stress even though both pathways were real.

Full and partial labels depend on sample size

Whether c′ is "significantly different from zero" depends largely on the sample size. In the CSCS, with 3,110 people, almost any direct effect is significant, so the result would nearly always be called partial mediation, while the same estimates in a sample of 100 people could be called full mediation. The labels describe statistical power more than they describe the pathway, so current guidance reports the size of the direct and indirect effects with confidence intervals instead (Rucker et al., 2011).

The causal assumptions are left implicit

The steps use the word "causal", yet they say nothing about temporal order or confounding of the mediator and the outcome, which Section 1 showed are needed for a causal reading.

The fourth limitation is the one most often met in practice. With 3,110 people, almost any direct effect is statistically significant, so the CSCS result would nearly always be labelled partial mediation, while the same estimates in a sample of 100 could be labelled full mediation. The same caution applies in reverse: a direct effect whose confidence interval includes zero in a small study shows imprecision, not the absence of a direct pathway, so it does not justify a claim of full mediation. Current guidance therefore reports the size of the direct and indirect effects with their confidence intervals instead of a label.

Reporting the indirect effect with a confidence interval requires a way of estimating its uncertainty, which is where the next subsection begins.

4.4 Estimating the Indirect Effect with mediate()

The mediate() function in the mediation package takes the mediator model and the outcome model, names the exposure (treat) and the mediator, and returns four quantities. Their names come from the counterfactual definitions in Section 1, which is why the word "causal" appears in them. Click each of the four cards below to see what each quantity is and the path, or combination of paths, to which it corresponds in a linear model.

ACMEClick to explore
ADEClick to explore
Total EffectClick to explore
Prop. MediatedClick to explore

4.4.1 Bootstrap Confidence Intervals for the Indirect Effect

An early direct test of a × b, the Sobel test, divides the product by an approximate standard error and compares the result with a normal distribution. The difficulty is that the sampling distribution of a product of two estimates is usually skewed. By this we mean that if the study were repeated many times, the values of a × b would not pile up symmetrically around the true value, as the bell curve assumes, but would trail off further on one side than the other. A symmetric normal interval can therefore be misleading. The bootstrap avoids this assumption (Preacher and Hayes, 2008). Instead of relying on a formula, it uses the data themselves to show how much the estimate would vary from sample to sample. It draws many new samples of the same size from the data with replacement, which means that a person can be picked more than once and others not at all, so each new sample is a slightly different version of the study. It then refits the models in each one, and takes the 2.5th and 97.5th percentiles of the resulting indirect effects as the 95% confidence interval. Because these percentiles come from the actual spread of the estimates, the interval can be asymmetric, with one end further from the estimate than the other. The bootstrap changes only how uncertainty is estimated; it does nothing about confounding or temporal order.

With 1,000 bootstrap samples, mediate() gives an ACME (the indirect effect) of −0.229 (95% CI −0.256 to −0.201), which matches a × b, an ADE (the direct effect) of −0.331 (95% CI −0.386 to −0.279) and a total effect of −0.560 (95% CI −0.618 to −0.509). Because the interval for the ACME excludes zero, the indirect association is unlikely to be due to sampling variation alone; an interval that included zero would mean that the data are consistent with no indirect association, although it would not prove that the pathway is absent. Figure 8.8 shows the plot drawn in Activity 8.3, in which the indirect, direct and total effects each appear with a 95% bootstrap confidence interval.

Plot from mediate() showing three point estimates with horizontal 95 percent confidence intervals: ACME about minus 0.23, ADE about minus 0.33 and total effect about minus 0.56, all to the left of a dashed line at zero.
Figure 8.8. The plot drawn by plot(med_result): the indirect effect (ACME), the direct effect (ADE) and the total effect, each with its 95% bootstrap confidence interval. All three intervals lie well to the left of zero.

4.4.2 The Proportion Mediated, Read with Caution

The proportion mediated is the ACME divided by the total effect, 0.41 here (95% CI 0.36 to 0.46): loneliness statistically accounts for about 41% of the association between support and depressive symptoms, and the direct effect makes up the remaining 59%. The figure is easy to communicate, and it is also easy to misuse. Because it is a ratio of two estimates, it becomes unstable when the total effect is small, and its interval can then be very wide. When the direct and indirect effects have opposite signs, they partly cancel (the inconsistent mediation of 4.3), and the proportion can exceed 1 or fall below 0, values that have no sensible reading as a share; the two parts are then reported separately. Evidence of an indirect association comes from the interval of the ACME, not from the size of the proportion mediated. In the CSCS the total effect is large and precisely estimated and both parts have the same sign, so the proportion is stable. It still describes how an association divides in these data, and it does not say that 41% of any benefit of support on mental health works through loneliness.

The estimates from mediate() rest on the assumption of no unmeasured mediator-outcome confounding. The next subsection examines how far the conclusion depends on that assumption.

5.1 Sensitivity Analysis for Unmeasured Mediator-Outcome Confounding

Section 1 showed that a causal reading of the indirect effect requires no unmeasured confounding of the mediator and the outcome, a condition that cannot be checked from the data. A history of depression, for example, could make a person both lonelier and more likely to report depressive symptoms now. The medsens() function asks how strong such confounding would need to be to change the conclusion (Imai, Keele and Tingley, 2010). Unmeasured confounding of loneliness and depressive symptoms would make the residuals of the mediator model and of the outcome model correlated. A residual is the part of a person's score that the model's predictors do not explain. If a history of depression raises both loneliness and depressive symptoms but is not in either model, its influence ends up in both sets of residuals, so people who are lonelier than the model predicts will also tend to have more symptoms than predicted. The sensitivity parameter ρ (rho) is the correlation between these two sets of residuals, and it therefore serves as a measure of how much unmeasured mediator-outcome confounding is present. The analysis assumes ρ = 0, which is the same as assuming no such confounding, and medsens() recalculates the indirect effect for a range of other values. Figure 8.9 plots the recalculated indirect effect across values of ρ, together with its confidence band.

Sensitivity plot. The horizontal axis is the sensitivity parameter rho from minus 0.9 to 0.9; the vertical axis is the average mediation effect. A black line with a grey confidence band rises from below minus 0.4 to above 0.4, passing minus 0.23 at rho of zero, marked by a dashed horizontal line, and crossing zero at rho of about 0.4.
Figure 8.9. The indirect effect (ACME) recalculated for values of the residual correlation ρ, with its 95% confidence band in grey. The dashed line marks the estimate under the usual assumption of ρ = 0 (−0.23). The indirect effect would reach zero if ρ were about 0.4.

The indirect effect falls to zero when ρ is about 0.4. An equivalent reading uses the second line of the summary: an unmeasured confounder would need to explain about 40% of the remaining variance in both loneliness and depressive symptoms to remove the indirect effect, and the line R^2_M*R^2_Y* at which ACME = 0 in the medsens() summary prints the product of these two shares, 0.16. That is a strong confounder, but a variable such as a history of depression could plausibly be one, so the result shows that the indirect association is reasonably resistant to this kind of confounding without ruling it out. The sensitivity analysis addresses only mediator-outcome confounding. It says nothing about the order of the variables in time, which remains the main limitation of the CSCS data.

The same three steps read a sensitivity result in any study. First, state what ρ means there: the residual correlation between the mediator and the outcome that an unmeasured common cause of the two would have to produce, beyond the covariates already in the models, to bring the indirect association to zero. Second, name a plausible unmeasured variable that affects both, such as a history of depression, personality, diet or general health consciousness; the sign of ρ shows the direction such a confounder would need to act in. Third, judge robustness from the size of ρ, ignoring its sign. The closer ρ is to zero, the weaker the confounding that would explain the result away, so a value of about 0.15 or 0.25 marks a fragile indirect association, while a value of about 0.4 needs a fairly strong confounder and marks a moderately robust one. Even a moderately robust result is reported as sensitive to confounding when a strong common cause is plausible, and not as established.

Activity 8.3 runs the whole analysis of 4.1 to 5.1 on the CSCS data. Run it along with the text: it fits the three regressions of Table 8.7, calculates the indirect effect by both methods, estimates the four quantities of mediate() with 1,000 bootstrap samples, and in its last question runs the sensitivity analysis with medsens(). Its questions ask you to interpret each path and effect with its interval in wording suited to a single survey, respond to a "partial mediation" claim and judge how robust the indirect association is.

R Activity 8.3: mediation, from three regressions to mediate()

Text version of the activity: the code of the run-along script, its console output and notes on reading it.

github_url <- "https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"
load(url(github_url))                      # survey data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
med_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,
  depression = data$WELLNESS_phq_score,
  age        = data$DEMO_age)
med_data <- na.omit(med_data)              # the same people in every model
nrow(med_data)
Console output
[1] 3110

The file is read straight from the web, and the 2021 wave is kept. The data frame keeps the support score (the exposure, 1 to 7), the UCLA loneliness score (the mediator, 3 to 9), the PHQ-2 depressive symptoms score (the outcome, 0 to 6) and age, and na.omit() keeps the 3,110 people with all four, so that every model uses the same people (the same 3,110 as in Section 2).

model_total <- lm(depression ~ support, data = med_data)           # path c
round(cbind(estimate = coef(model_total), confint(model_total)), 3)
model_a <- lm(loneliness ~ support, data = med_data)               # path a
round(cbind(estimate = coef(model_a), confint(model_a)), 3)
model_b <- lm(depression ~ support + loneliness, data = med_data)  # b and c'
round(cbind(estimate = coef(model_b), confint(model_b)), 3)
Console output
estimate 2.5 % 97.5 % (Intercept) 4.817 4.571 5.063 support -0.560 -0.608 -0.511 estimate 2.5 % 97.5 % (Intercept) 8.660 8.406 8.913 support -0.626 -0.676 -0.576 estimate 2.5 % 97.5 % (Intercept) 1.650 1.294 2.006 support -0.331 -0.380 -0.282 loneliness 0.366 0.334 0.397

Each model is printed as its coefficients with 95% confidence intervals, using cbind(estimate = coef(model), confint(model)). Path c, the total effect: each point of support is associated with a PHQ-2 score 0.560 points lower (95% CI −0.608 to −0.511). Path a: each point of support is associated with a loneliness score 0.626 points lower (95% CI −0.676 to −0.576). The outcome model gives two paths. Path b: among people with the same support score, each point of loneliness is associated with a PHQ-2 score 0.366 points higher (95% CI 0.334 to 0.397). Path c′, the direct effect: among people with the same loneliness score, each point of support is associated with a PHQ-2 score 0.331 points lower (95% CI −0.380 to −0.282). The direct effect is smaller than the total effect of −0.560, because part of the total runs through loneliness.

a        <- coef(model_a)["support"]
b        <- coef(model_b)["loneliness"]
c_total  <- coef(model_total)["support"]
c_direct <- coef(model_b)["support"]
a * b                  # product of coefficients
c_total - c_direct     # difference method
Console output
support -0.2289081 support -0.2289081

Both methods give an indirect effect of −0.2289. R labels both results support because the first number in each calculation was taken from the support coefficient.

library(mediation)     # install.packages("mediation") once, if needed
set.seed(2021)         # makes the bootstrap repeatable
med_result <- mediate(model_a, model_b, treat = "support",
                      mediator = "loneliness", boot = TRUE, sims = 1000)
summary(med_result)
plot(med_result, xlim = c(-0.7, 0))   # the three effects with 95% CIs
Console output
Loading required package: MASS Loading required package: Matrix Loading required package: mvtnorm Loading required package: sandwich mediation: Causal Mediation Analysis Version: 4.5.1 Running nonparametric bootstrap Causal Mediation Analysis Nonparametric Bootstrap Confidence Intervals with the Percentile Method Estimate 95% CI Lower 95% CI Upper p-value ACME -0.22891 -0.25565 -0.20137 < 2.2e-16 *** ADE -0.33078 -0.38639 -0.27886 < 2.2e-16 *** Total Effect -0.55969 -0.61821 -0.50883 < 2.2e-16 *** Prop. Mediated 0.40899 0.35523 0.46428 < 2.2e-16 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Sample Size Used: 3110 Simulations: 1000
Plot from mediate() showing three point estimates with horizontal 95 percent confidence intervals: ACME about minus 0.23, ADE about minus 0.33 and total effect about minus 0.56, all to the left of a dashed line at zero.

This part uses the mediation package; install it once with install.packages("mediation") if it is not yet installed. The bootstrap refits the two models 1,000 times, so mediate() takes about 15 seconds on a laptop, and set.seed(2021) makes the resampling repeatable, so your numbers match the ones above. Reading the output: the ACME row is the indirect effect, −0.229 (95% CI −0.256 to −0.201), which matches a × b; the ADE row is the direct effect, −0.331 (95% CI −0.386 to −0.279); the Total Effect row is −0.560 (95% CI −0.618 to −0.509); and Prop. Mediated is 0.41 (95% CI 0.36 to 0.46). The intervals come from the 1,000 bootstrap samples (the percentile method). The p-values are printed as below 2.2 × 10−16, the smallest value R displays; bootstrap p-values are approximate, and the intervals carry the main information. The last line draws the plot of the three effects (Figure 8.8).

Question 3 asks you to run the sensitivity analysis yourself, at the end of the script: sens <- medsens(med_result, rho.by = 0.1, effect.type = "indirect", sims = 100) and then summary(sens). In its output, the Sensitivity Region table lists the values of ρ at which the confidence interval for the ACME includes zero; with steps of 0.1 (rho.by = 0.1), the threshold is located to the nearest 0.1. The line R^2_M*R^2_Y* at which ACME = 0 gives the same threshold as the product of the shares of remaining variance in loneliness and in depressive symptoms that a confounder would need to explain.

Files for this activity Data Code Answer key

R Reflect on what you just ran

Answer each question from your own output, as on the final exam: interpret each path and effect with its interval, use wording suited to a single survey, and judge the sensitivity analysis.

1. In plain words, what do paths a and b show? Take each path from the right model. Read the indirect effect from the product-of-coefficients line (a * b) and the difference-method line (c_total - c_direct), and explain why the two agree here. A colleague who uses the older causal steps concludes that loneliness "only partially mediates" the association, because the direct effect is still significant. Respond.

Model answerPath a, the support coefficient in the mediator model (model_a), is −0.626 (95% CI −0.676 to −0.576): each one-point higher support score is associated with a loneliness score about 0.63 points lower. Path b, the loneliness coefficient in the outcome model (model_b), is 0.366 (95% CI 0.334 to 0.397): among people with the same support score, each one-point higher loneliness score is associated with a depressive symptoms score about 0.37 points higher. R prints the same indirect effect, −0.2289, for the product of coefficients (a * b) and for the difference method (c_total - c_direct, the total effect minus the direct effect). They agree exactly because all three models are linear regressions fitted to the same 3,110 people, so the total effect equals the direct effect plus a × b; with a logistic outcome model, or with different people in different models, the two can differ. The colleague's label depends mainly on sample size: with 3,110 people even a small direct effect is significant, so "partial mediation" describes statistical power more than the pathway, and the causal steps never test a × b itself. Instead of a label, report the size of the direct effect (−0.331, 95% CI −0.380 to −0.282) and of the indirect effect (−0.229) with confidence intervals; the bootstrap in the next part of the activity gives the interval for the indirect effect.

2. Interpret the indirect effect (the ACME row) and its confidence interval, in wording suited to a single survey. Is there evidence of an indirect association? Interpret the proportion mediated, and give one reason to read it with caution. Why is a bootstrap interval used for the indirect effect?

Model answerThe ACME, the indirect effect, is −0.229 (95% bootstrap CI −0.256 to −0.201): of the association between support and depressive symptoms, about 0.23 points of the depressive symptoms score per point of support runs through loneliness. Yes, there is evidence of an indirect association: the 95% bootstrap interval does not include 0. Because all three variables were measured in the same survey, loneliness is described as "statistically accounting for" part of the association, not as the route by which support lowers depressive symptoms. The proportion mediated is 0.41 (95% CI 0.36 to 0.46): loneliness statistically accounts for about 41% of the total association between support and depressive symptoms (the Prop. Mediated row gives the ACME as a share of the total effect). Caution: it is a ratio of two estimates, so it becomes unstable when the total effect is small or uncertain and can fall outside 0 to 1 when the direct and indirect effects have opposite signs; here the total is large and precise and both parts are negative, so 0.41 is stable. A bootstrap interval is used because the sampling distribution of a product of two estimates (a × b) is usually skewed, so a symmetric normal interval such as the Sobel test's can mislead; the bootstrap refits the models in 1,000 resamples and takes the 2.5th and 97.5th percentiles, without assuming symmetry.

3. Run your own code: at the end of the script, type the two lines below and run them. Interpret the value of ρ at which the ACME equals zero, and name an unmeasured variable that could produce such a correlation. Does this result make the indirect association robust? Explain briefly.
sens <- medsens(med_result, rho.by = 0.1, effect.type = "indirect", sims = 100)
summary(sens)

Model answerThe summary reports Rho at which ACME = 0: 0.4. The analysis assumes no unmeasured confounding of loneliness and depressive symptoms (ρ = 0), which even randomizing support would not guarantee, because randomizing the exposure does not randomize the mediator. An unmeasured confounder of loneliness and depressive symptoms would have to induce a residual correlation of about 0.4 between them (a confounder explaining about 40% of the remaining variance in each; the output prints the product of these shares, R^2_M*R^2_Y*, as 0.16) to reduce the indirect association to zero. A plausible candidate is a history of depression (or a personality trait such as neuroticism), which could raise both loneliness and current depressive symptoms. The result is moderately robust: a residual correlation of 0.4 needs a fairly strong confounder, so weak confounding would not explain it away, but a strong common cause such as a history of depression is plausible here, so the indirect association should be reported as sensitive to that possibility, not as established. The sensitivity analysis also says nothing about the order of the variables in time, which this single survey cannot establish.
Saved.

The output of Activity 8.3 reproduces each estimate used in this section, from the paths in Figure 8.6 to the ρ of about 0.4 in Figure 8.9. With the estimates and their sensitivity to confounding in hand, the remaining task is to report the analysis.

7.3 Reporting a Mediation Analysis

The AGReMA statement (Lee et al., 2021) gives a checklist for reporting mediation analyses of trials and observational studies. Its main elements can be embedded in a few sentences: the assumed causal structure (a DAG), the timing of each measurement, the covariates in the mediator and outcome models, the estimation method and number of bootstrap samples, the indirect, direct and total effects with confidence intervals, a sensitivity analysis, and the limitations of the design.

Worked Example 8.1 applies this checklist to the CSCS analysis. As you read it, notice which AGReMA elements it covers, and check each verb against the wording for cross-sectional data in Table 8.2 of Section 1.

Worked Example 8.1: A results paragraph for the CSCS analysis

"We examined whether loneliness statistically accounted for part of the association between perceived social support and depressive symptoms among 3,110 participants in the 2021 wave of the Canadian Social Connection Survey. Indirect, direct and total associations were estimated with linear mediator and outcome models and the mediation package in R, with 95% confidence intervals from 1,000 nonparametric bootstrap samples. Each additional point of support was associated with a PHQ-2 score 0.56 points lower (95% CI −0.62 to −0.51). The indirect association through loneliness was −0.23 (95% CI −0.26 to −0.20) and the direct association was −0.33 (95% CI −0.39 to −0.28), so loneliness statistically accounted for about 41% of the total association (95% CI 36% to 46%). A sensitivity analysis indicated that the indirect association would be removed by unmeasured confounding of loneliness and depressive symptoms that induced a residual correlation of about 0.4. Because all measures were collected at the same time, these results describe a pattern of associations consistent with a pathway through loneliness and do not establish its direction."

The paragraph covers the sample and its timing, the method and number of bootstrap samples, all three effects with intervals, the proportion mediated, the sensitivity analysis and the limitation of the design, and every verb ("was associated with", "statistically accounted for") describes an association. In a manuscript the DAG and the covariates in each model would be added. When you write your own sentences, check each verb in the same way: "reduced", "caused" and "works through" do not suit cross-sectional data.

The narrated walkthrough in the red card below offers a second route through the regressions and the mediate() analysis of Activity 8.3.

Learn to do this in R

Narrated R walkthrough: Mediation and Moderation

The first half of the Mediation and Moderation walkthrough runs the three regressions, the a × b calculation and the mediate() analysis of this section line by line, with narration and diagrams of each path.

Open the Mediation and Moderation walkthrough

This section has estimated the indirect association of social support with depressive symptoms through loneliness, −0.23 PHQ-2 points per point of support or about 41% of the total, and it has shown that this association would fall to zero if mediator-outcome confounding produced a residual correlation of about 0.4. Section 4 writes the same model as a path model and extends it to a second outcome. The key takeaways and knowledge check below review this material.

Key Takeaways

  • 4.1 Three ordinary linear regressions give every path in a simple mediation diagram. The total-effect model, lm(depression ~ support), gives c; the mediator model, lm(loneliness ~ support), gives a; and the outcome model, lm(depression ~ support + loneliness), gives b (its loneliness coefficient) and c′ (its support coefficient). Path b is read among people with the same exposure and c′ among people with the same mediator value, so interpret them that way, for example "among people with the same support score, each point of loneliness is associated with a PHQ-2 score 0.366 points higher". A common slip in output questions is taking a coefficient from the wrong model, so match each path to its model before you interpret it. In a real analysis the confounders from the DAG are added to the mediator and outcome models, and each path is then described as adjusted for them.
  • 4.2 The indirect effect can be obtained in two ways: the product-of-coefficients method multiplies a by b, and the difference method subtracts the direct effect from the total effect, c − c′. In Activity 8.3, R computes both, with a * b and c_total - c_direct, and prints −0.229 for each. They agree exactly only when the mediator and outcome models are linear regressions fitted to the same people; with a logistic outcome model, or with different people in different models, the two can differ, which is one reason mediate() uses the counterfactual approach. Two printed values that agree confirm that the linear models were fitted to the same people, and it pays to read the signs: a negative a times a positive b gives a negative indirect effect, meaning that more support goes with less loneliness, which goes with fewer symptoms.
  • 4.3 You will still meet the Baron and Kenny causal steps in published papers: mediation was claimed when c, a and b were each significant and c′ was smaller than c, and it was called "full" if c′ fell to zero and "partial" otherwise. Methodologists no longer recommend these steps as a test, because they never test the product a × b, they have low power, they rule out inconsistent mediation (where direct and indirect effects of opposite sign cancel and leave a total close to zero), and they leave the causal assumptions unstated. The "full" and "partial" labels mainly reflect sample size: with 3,110 people almost any direct effect is significant, while the same estimates in a sample of 100 might be labelled full mediation. So when a question quotes a claim that a variable "fully mediates" an association because c′ was not significant, critique the label and report the size of the direct and indirect effects with their confidence intervals instead.
  • 4.4 The mediate() function takes the mediator and outcome models and reports four quantities: the ACME (the indirect effect, a × b in linear models), the ADE (the direct effect, c′), the total effect and the proportion mediated. The indirect effect is tested with a bootstrap confidence interval because the sampling distribution of a product of two estimates is usually skewed, so a symmetric normal interval such as the Sobel test's can mislead; the bootstrap refits the models in many resamples of the data (1,000 here) and takes the 2.5th and 97.5th percentiles. Read the interval first: the CSCS ACME is −0.229 (95% CI −0.256 to −0.201), and because the interval excludes zero the indirect association is unlikely to be due to sampling variation alone. Treat the proportion mediated (here 0.41) with care, because it is a ratio of two estimates that becomes unstable when the total effect is small and can fall below 0 or above 1 when the direct and indirect effects have opposite signs. If a question gives a proportion mediated outside 0 to 1, explain the opposite signs or the small total effect rather than reading it as a share.
  • 5.1 Because the assumption of no unmeasured mediator-outcome confounding cannot be checked from the data, medsens() asks how strong such confounding would have to be to change the conclusion. Its sensitivity parameter ρ (rho) is the correlation between the residuals of the mediator and outcome models that an unmeasured common cause would need to induce to bring the indirect effect to zero; the main analysis assumes ρ = 0. To interpret it in any study, state what ρ means, name a plausible confounder of the mediator and the outcome (such as a history of depression), and judge robustness from the size of ρ, ignoring its sign. A value of about 0.15 or 0.25 marks a fragile indirect association, while a value of about 0.4, as in the CSCS, needs a fairly strong confounder and marks a moderately robust one, which is still reported as sensitive to confounding rather than as established. Remember too that ρ addresses only mediator-outcome confounding and says nothing about temporal order.
  • 7.3 A complete mediation report lets the reader see both the estimates and their limits. Following the AGReMA checklist, it states the assumed causal structure (the DAG), the timing of each measurement, the covariates in the mediator and outcome models, the method and number of bootstrap samples, the indirect, direct and total effects with confidence intervals, the sensitivity analysis and the limitations of the design. Worked Example 8.1 is a model to adapt: it gives the indirect association as −0.23 (95% CI −0.26 to −0.20), says that loneliness "statistically accounted for about 41%" of the total, reports the ρ of about 0.4, and closes by saying that the results are consistent with a pathway through loneliness but do not establish its direction. When you write your own sentences, check each verb: "was associated with" and "statistically accounted for" suit cross-sectional data, while "reduced", "caused" and "works through" do not.
Knowledge check: this section

1. A study of 900 older adults asks whether hearing loss (per 10 dB) is associated with depressive symptoms partly through loneliness. Three linear regressions fitted to the same people give the coefficients below, and R computes the indirect effect by both methods. Which statement is correct?

Model in RCoefficientEstimate
lm(dep ~ hearing)hearing0.48
lm(lonely ~ hearing)hearing0.40
lm(dep ~ hearing + lonely)lonely0.45
lm(dep ~ hearing + lonely)hearing0.30
> a * b                 # product of coefficients
hearing
   0.18
> c_total - c_direct    # difference method
hearing
   0.18 
This swaps the two paths and combines them wrongly. Path a is the hearing coefficient in the mediator model and path b is the lonely coefficient in the outcome model, and the indirect effect is their product, not their sum.
The paths are read correctly, but the hearing coefficient in the outcome model is the direct effect, the part that remains with loneliness held constant. The indirect effect is the product of a and b.
The indirect effect is right, but a share of the total divides the indirect effect by the total effect, as the proportion mediated does. Dividing by the direct effect gives a different, unhelpful ratio.
Each path is read from the right model: a from the mediator model and b, among people with the same hearing loss, from the outcome model. The product and difference methods agree because the models are linear and fitted to the same people.
The correct statement reads a, b and the indirect effect as 0.40, 0.45 and 0.18. Path a is the hearing coefficient in the mediator model (loneliness on hearing), 0.40. Path b is the lonely coefficient in the outcome model, 0.45, read among people with the same hearing loss because hearing is also in that model, and the hearing coefficient in the same model is the direct effect c′ = 0.30. R prints the indirect effect as 0.18 by the product method (a × b) and by the difference method (c − c′), and the two agree because all three models are linear and fitted to the same people. A share of the total divides the indirect effect by the total effect (0.48), as the proportion mediated does, so the option that divides by the direct effect is wrong, and the option giving 0.30 confuses the direct effect with the indirect effect. (Section 3, 4.1 Three Regressions, Four Paths, Table 8.7 and Figure 8.6; 4.2 Product-of-Coefficients and Difference Methods and Eq 8.4; Activity 8.3; Objectives 4.1 and 4.2)

2. In a study of 5,000 employees, the indirect association of job strain with sick days through burnout is 0.21 (95% bootstrap CI 0.17 to 0.25) and the direct association is 0.09 (95% CI 0.03 to 0.15). A colleague who follows the Baron and Kenny steps writes: "Burnout only partially mediates the effect, because the direct effect is still significant." Which response is best?

Whether the direct effect reaches significance depends mainly on sample size, so with 5,000 people almost any direct association is significant. The label describes power more than the pathway, and the steps never test the indirect effect itself.
The "full" and "partial" labels rest on whether the direct effect is significant, which depends mainly on sample size. Reporting the size of each part with its interval describes the pathway directly.
Comparing the sizes of the parts does not turn a result into full mediation, and the direct association here has an interval that excludes zero. The labels are themselves not recommended; the sizes and intervals are reported instead.
Meeting the first step does not repair the problems with the causal steps: the labels still depend on sample size, and the steps never test the indirect effect. The first step can also miss inconsistent mediation.
The best response replaces the label with the size of each part. The causal steps call a result "partial mediation" when the direct effect c′ is still significant, but whether c′ reaches significance depends mainly on the sample size: with 5,000 people even a small direct association is significant, and the same estimates in a small sample might have been called "full" mediation. The label therefore describes statistical power more than the pathway, and the steps never test a × b itself. The report gives each part with its interval: an indirect association of 0.21 (0.17 to 0.25) and a direct association of 0.09 (0.03 to 0.15), both in sick days per unit of job strain. The last option is tempting, but meeting the first step does not repair these problems. (Section 3, 4.3 The Limits of the Baron and Kenny Causal Steps, its accordion panels and the paragraph after them; Objective 4.3)

3. A single survey of 600 commuters was analysed with mediate() and 1,000 bootstrap samples, with commuting time (per 10 minutes) as the exposure, sleep duration as the mediator and a fatigue score as the outcome (output below). The draft report says: "Sleep fully mediated the effect of commuting on fatigue: 60% of the effect works through sleep, and the direct effect was not significant." Which revision is most appropriate?

QuantityEstimate95% bootstrap CI
ACME0.060.03 to 0.10
ADE0.04−0.05 to 0.13
Total Effect0.100.01 to 0.19
Prop. Mediated0.600.18 to 3.10
An ADE interval that includes zero reflects imprecision in 600 people, not an absent direct pathway; it also allows a direct association larger than the indirect one. "Fully mediated" mistakes a lack of precision for an absence.
A single survey cannot establish that commuting causes fatigue through sleep, so causal wording such as "increased" and "shortening" is not supported. The 60% is also too imprecise to present as a firm share.
The revision gives each part with its interval, uses associational wording and flags that the proportion mediated is imprecise because the total association is small and uncertain. That is how the lesson reports a mediation result.
The proportion mediated is an unstable ratio here, with an interval that reaches an impossible value, so it is not a reliable share. A direct interval that includes zero shows imprecision, not that there is no direct association.
The correct revision reports each part with its interval, uses associational wording and flags the imprecise share. The proportion mediated that mediate() prints (0.60) is the ACME divided by the total effect. It is a ratio whose denominator is small and imprecise here (the total's interval runs from 0.01, close to zero, to 0.19), so the ratio is unstable and its interval reaches an impossible 3.10; the 60% describes roughly how an association divides, not a precise share of an effect. An ADE interval that includes zero reflects imprecision in 600 people, not an absent direct pathway: it also reaches 0.13, more than twice the ACME, so "full mediation" and "no direct association" (the first and last options) mistake a lack of precision for an absence. The second option claims a causal pathway that a single survey cannot show. (Section 3, 4.3 The Limits of the Baron and Kenny Causal Steps, the paragraph after the accordion; 4.4.2 The Proportion Mediated, Read with Caution; 7.3 Reporting a Mediation Analysis and Worked Example 8.1; Objectives 4.3, 4.4 and 7.3)

4. A colleague computes a 95% interval for an indirect effect as a × b ± 1.96 × SE, using the Sobel standard error, and asks why the lesson uses a bootstrap interval instead. What is the best reply?

The product of two estimates usually has a skewed sampling distribution, so a symmetric normal interval can mislead. The bootstrap refits the models in many resamples and takes percentiles of the indirect effects, so its interval can be asymmetric.
The bootstrap changes only how uncertainty is estimated. It does nothing about unmeasured confounding of the mediator and the outcome, which is why a sensitivity analysis is still needed.
Resampling the same cross-sectional data cannot establish the order of variables in time. The bootstrap addresses the shape of the sampling distribution, not temporal order.
The lesson's reason for preferring the bootstrap is the skewed distribution of a × b, not a sample-size limit on the Sobel test. The Sobel test assumes a symmetric normal distribution that the product usually lacks.
The best reply is that a × b is usually skewed, and the bootstrap builds the interval from the resampled estimates. The Sobel approach divides a × b by an approximate standard error and assumes a normal, symmetric sampling distribution, but the product of two estimates usually has a skewed distribution, so a symmetric interval can be misleading. The bootstrap draws many samples of the same size with replacement, refits the mediator and outcome models in each, and takes the 2.5th and 97.5th percentiles of the resulting indirect effects as the 95% interval, so the interval can be asymmetric. The bootstrap changes only how uncertainty is estimated: it does nothing about confounding or temporal order (the second and third options), which is why a sensitivity analysis and careful wording are still needed. (Section 3, 4.4.1 Bootstrap Confidence Intervals for the Indirect Effect and Activity 8.3; Objective 4.4)

5. A mediation analysis of food insecurity and depressive symptoms, with sleep problems as the mediator and both models adjusted for age and income, reports from medsens() that the ACME would equal zero at ρ = 0.15. Which interpretation is best?

ρ is not the proportion mediated. It is the residual correlation between the mediator and outcome models that an unmeasured confounder would have to produce to bring the indirect effect to zero.
ρ is not the observed correlation between sleep problems and depressive symptoms. It describes the residual correlation that unmeasured mediator-outcome confounding would need to induce, beyond the covariates, to remove the indirect effect.
This reverses the reading. The closer ρ is to zero, the weaker the confounding needed to explain the indirect association away, so a small value marks a fragile result rather than a robust one.
ρ is the residual correlation an unmeasured common cause of the mediator and outcome would need to produce to remove the indirect effect. A value near zero, such as 0.15, means weak confounding would suffice, so the result is fragile.
The best interpretation is that weak mediator-outcome confounding could remove the indirect association, so it is fragile. ρ is the correlation between the residuals of the mediator model and the outcome model that an unmeasured mediator-outcome confounder would have to produce, beyond age and income, to bring the indirect effect (ACME) to zero. A plausible confounder must affect both sleep problems and depressive symptoms, such as chronic pain or a history of depression. Robustness is judged from the size of ρ: the closer it is to zero, the weaker the confounding that would explain the result away, so 0.15 marks a fragile indirect association, whereas a value of about 0.4 (as in the CSCS) would need a fairly strong confounder. The third option reverses this reading, and the first two confuse ρ with the proportion mediated or with the observed correlation. (Section 3, 5.1 Sensitivity Analysis for Unmeasured Mediator-Outcome Confounding, Figure 8.9 and the three steps for reading ρ; Objective 5.1)

6. A single survey of 1,850 adults asked whether daily servings of fruit and vegetables (the mediator) carry part of the association between food insecurity (0 to 10, higher means less secure access to food) and self-rated health (0 to 100, higher is better). The mediator and outcome models were both adjusted for household income, age and sex, and mediate() with 1,000 bootstrap samples gave the output below. Which sentence suits the report?

QuantityEstimate95% bootstrap CI
ACME−0.60−0.83 to −0.39
ADE−1.40−1.90 to −0.90
Total Effect−2.00−2.48 to −1.52
Prop. Mediated0.300.19 to 0.43
The sentence gives the ACME with its bootstrap interval, which excludes zero, reads the proportion mediated as a share of the total association, and uses associational wording suited to one survey.
All three variables come from one survey, so "worsened" and "by reducing" claim a direction and a cause that the design cannot show. The result should be worded as a statistical decomposition of an association.
Evidence of an indirect association comes from the interval of the ACME, which excludes zero here, not from whether the proportion mediated exceeds one half.
Adjusting for income, age and sex does not remove unmeasured confounding of diet and health or establish temporal order. A claim about what improving diet would do is causal and not supported by one survey.
The correct sentence gives the indirect association with its bootstrap interval, the share of the total and associational wording. The ACME row is the indirect association, −0.60 health points per point of food insecurity, and its 95% bootstrap interval (−0.83 to −0.39) excludes zero, so there is evidence of an indirect association; the proportion mediated (0.30) means that intake statistically accounts for about 30% of the total association. Evidence of an indirect association comes from the interval of the ACME, not from the size of the proportion mediated (the third option). All three variables were measured in one survey, so wording such as "worsened" or "would improve" claims a direction and a cause that the design cannot show, and adjusting for income, age and sex does not remove unmeasured confounding of diet and health or establish temporal order (the second and last options). (Section 3, 4.4 Estimating the Indirect Effect with mediate(), 4.4.1 and 4.4.2; 7.3 Reporting a Mediation Analysis and Worked Example 8.1; Objectives 4.4 and 7.3)
● Complete the quiz to continue.
Section 4 of 4

Path Analysis and the Road to Structural Equation Modelling

⏱ Estimated time: 50 minutes
Lesson 8 · Section 4

Path Analysis and the Road to Structural Equation Modelling

A path model writes several regressions as one diagram and fits them together, so that whole models can be tested and compared.

Path diagrams

The symbols of a path diagram

Rectangle

It is an observed variable, such as the loneliness score.

Oval

It is a latent variable, measured through several items.

Single-headed arrow

It is a regression path from a predictor to an outcome.

Double-headed arrow

It is a covariance between two variables or their residuals.

lavaan syntax

Writing a model as text

OperatorMeaningExample
~is regressed onloneliness ~ a * support
~~covaries withdepression ~~ anxiety
=~is measured byLonely =~ item1 + item2 + item3
:=is defined asindirect := a * b
Two outcomes

Model 1 and Model 2

Fit measureModel 1 (no direct paths)Model 2 (direct paths)Usual guide
Chi-square (df)173.8 (2), p < 0.0010 (0)p above 0.05
CFI0.94210.95 or higher
TLI0.827not defined0.95 or higher
RMSEA0.16600.06 or lower
SRMR0.07100.08 or lower
Model comparison

The direct paths are needed

173.8
chi-square difference on 2 df (p < 0.001)
32,864
AIC for Model 2, compared with 33,033 for Model 1 (lower is better)
Reporting

The chosen model, standardized

Support Loneliness Depression Anxiety −0.40 0.38 0.37 −0.22 −0.15 0.47 R² = 0.16 R² = 0.26 R² = 0.20
Structural equation modelling

Adding a measurement model

Measurement model

A latent Lonely factor is measured by three UCLA items (standardized loadings 0.69, 0.69 and 0.76).

Structural model

Support → Lonely is −0.46 and Lonely → depression is 0.47, both stronger than with the observed score.

The model fits well: chi-square 38.9 on 4 df, CFI 0.991, RMSEA 0.053 and SRMR 0.016.

Lesson summary

Next: the knowledge check and the final assessment

  • A DAG sets the role of each third variable before any model is fitted.
  • Moderation is tested with an interaction and reported with simple slopes.
  • Mediation splits an association into direct and indirect parts, reported with bootstrap intervals and a sensitivity analysis.
  • A path model fits several equations at once, and a structural equation model adds latent variables.

Overview

Sections 2 and 3 fitted one regression at a time. A path model writes all of the regressions in an analysis as one diagram and estimates them together. This has three advantages. Several outcomes and several pathways can be handled at once, the indirect effects can be defined and tested inside the model, and a whole model can be compared with a simpler one that leaves some paths out. This section introduces the symbols of a path diagram and the syntax of the lavaan package (Rosseel, 2012), rebuilds the mediation model from Section 3, extends it to two outcomes, judges and compares the fit of two versions, and reads the results of the chosen model. It then adds a latent variable, which turns the path model into a structural equation model (SEM) and connects path analysis to confirmatory factor analysis, and it closes with the reporting of a path model.

Learning Objectives

  • 6.1 Draw and read a path diagram using the conventions for observed variables, latent variables, paths and covariances.
  • 6.2 Read a path model written in lavaan syntax with labelled paths and a defined indirect effect.
  • 6.3 Judge the fit of a path model from the chi-square test and the CFI, TLI, RMSEA and SRMR read together, and compare two nested models with a chi-square difference test and the AIC.
  • 6.4 Interpret the indirect paths with bootstrap confidence intervals, the standardized coefficients and the R-squared values of a path model.
  • 6.5 Explain how adding a measurement model with latent variables extends path analysis to structural equation modelling, and what it cannot fix.
  • 7.4 Report a path model with a figure, estimates and intervals, without relying on the labels "full" and "partial" mediation and without causal overstatement.

6.1 Path Diagrams

Path analysis was introduced by the geneticist Sewall Wright (1921) as a way of tracing correlations through chains of causes. A path diagram uses a small set of symbols, and the same symbols are used in SEM. Table 8.8 lists the symbols with their meaning and an example of each from this section.

Table 8.8. The symbols of a path diagram.

SymbolMeaningExample in this section
RectangleAn observed variable, recorded in the datasetThe loneliness score, the PHQ-2 score
OvalA latent variable, measured indirectly through several observed itemsA loneliness factor measured by three UCLA items
Single-headed arrowA regression path from a predictor to an outcomeSupport → loneliness
Double-headed arrowA covariance (or correlation) with no direction assumedThe residuals of depression and anxiety
Residual (often a small circle or an unlabelled arrow)The part of an endogenous variable that the model does not explainEverything else that affects loneliness

A variable with no arrows pointing at it is exogenous: its causes lie outside the model, and in this section support is the only exogenous variable. A variable with at least one arrow pointing at it is endogenous, and the model has an equation and a residual for it. Loneliness, depressive symptoms and anxiety symptoms are endogenous. Each single-headed arrow in the diagram is a coefficient in one of those equations, so a path model with three endogenous variables is a set of three regressions fitted together. When reading a diagram, counting the endogenous variables shows how many equations the model has.

To estimate these regressions together, the diagram has to be written as a model that R can fit.

6.2 Writing a Path Model in lavaan

6.2.1 Operators and Labels

The lavaan package describes a model as a block of text inside single quotes, with one equation or relationship on each line. Four operators cover everything in this lesson, and Table 8.9 sets out how each is read, an example of each and the element of the path diagram that each one produces.

Table 8.9. The four lavaan operators used in this lesson.

OperatorRead asExampleIn the diagram
~is regressed onloneliness ~ supportArrow from support to loneliness
~~covaries withdepression ~~ anxietyDouble-headed arrow
=~is measured byLonely =~ companionship + left_out + isolatedOval with arrows to its items
:=is defined asindirect := a * bA quantity computed from labelled paths

In a line written with ~, the outcome is on the left and each predictor on the right sends a single-headed arrow to it. A label is written in front of a predictor with an asterisk, as in loneliness ~ a * support, which names the path from support to loneliness a. Labels make it possible to define the indirect effect (a * b) and the total effect (c + a * b) inside the model, and lavaan then reports their estimates and standard errors with the other parameters. A defined quantity is reported with the estimates but is not drawn as an arrow in the diagram. The model is fitted with sem(model, data = ...).

6.2.2 The Simple Mediation Model in lavaan

Activity 8.4, at the end of 6.5, rebuilds the mediation model from Section 3 in lavaan. The path model uses people with complete data on four variables (support, loneliness, depressive symptoms and anxiety symptoms), because the activity goes on to add anxiety as a second outcome. This leaves 3,099 people, eleven fewer than in Sections 2 and 3, so the estimates differ slightly in the third decimal place.

In its output, the labelled paths appear under Regressions: a = −0.627, b = 0.365 and c = −0.329, close to the linear regressions of Section 3 (−0.626, 0.366 and −0.331). Labels are only names, so it is worth checking what each points to: in lavaan the label c names the direct path, which Section 3 called c′. Under Defined Parameters, the indirect effect is a × b = −0.229 and the total effect is c + a × b = −0.559, each with a standard error, and the dots before .loneliness and .depression under Variances mark residual variances.

The simple mediation model has zero degrees of freedom. In a path model, the degrees of freedom are the number of pieces of information that the data supply minus the number of parameters the model estimates. The information here is the set of variances and covariances among the variables, which summarize how each variable spreads and how each pair moves together. The simple mediation model estimates five parameters (three paths and two residual variances), and the data supply exactly five pieces of information about the relationships among the three variables, once the variance of support is set aside. A model like this is called saturated or just-identified. By this we mean that the model has as many free parameters as there are pieces of information, so it can always adjust them to match the data perfectly, in the same way that a straight line can always be drawn through two points. It reproduces the observed covariances exactly, so its chi-square is 0 and its fit cannot be tested: a model that cannot fail a test gives no evidence by passing it. Fit becomes testable only when a model leaves some paths out, which is what the next subsection does.

6.3 Judging Fit and Comparing Two Models

The CSCS also includes the two-item Generalized Anxiety Disorder scale (GAD-2; Kroenke et al., 2007), scored from 0 to 6. The analyst asks whether loneliness links support to both depressive and anxiety symptoms, and compares two models. Figure 8.10 draws the two models in one diagram, with the direct paths that only Model 2 contains shown as dashed arrows.

Support Loneliness Depression (PHQ-2) Anxiety (GAD-2) c1 (Model 2 only) c2 (Model 2 only) a b1 b2 Model 1 has the solid paths only. Model 2 adds the two dashed direct paths.
Figure 8.10. Model 1 allows support to be related to the two outcomes only through loneliness. Model 2 adds a direct path from support to each outcome (c1 and c2). In both models, the curved double-headed arrow lets the residuals of depression and anxiety covary, because the two outcomes share causes that the model does not include.

Model 1 contains no direct paths from support to the outcomes. It corresponds to what the Baron and Kenny tradition calls full mediation. Model 2 adds the direct paths and labels every path so that the two indirect effects can be defined. Both models include depression ~~ anxiety, which allows the parts of depressive and anxiety symptoms that loneliness and support leave unexplained to be correlated. Leaving this line out would assume that nothing else links the two outcomes, which is implausible for two measures of distress. Activity 8.4 fits both models, and the two parts below read their fit and their comparison.

6.3.1 Reading the Fit Indices

Fit indices describe how well a model with some paths left out reproduces the observed covariances. By this we mean the following. Once a model is fitted, its estimated paths imply what the variances and covariances among the variables ought to be; for example, if support is linked to depressive symptoms only through loneliness, the model implies a particular covariance between support and depressive symptoms. These implied values are then compared with the covariances actually observed in the data. If leaving the paths out was reasonable, the two sets of values will be close, and if it was not, they will differ. Each fit index summarizes that difference in its own way. The guides for good fit in Table 8.10 follow Hu and Bentler (1999), and the description of an RMSEA up to 0.08 as acceptable and above 0.10 as poor follows Browne and Cudeck (1993). All of these guides are rules of thumb, and they work best when several indices are read together (Kline, 2016).

Table 8.10. Common fit indices, what each measures, the usual guide for good fit and the value for Model 1.

IndexWhat it measuresUsual guide for good fitModel 1
Chi-square testWhether the model's covariances differ from the observed ones; in large samples it rejects almost every modelp above 0.05173.8 on 2 df, p < 0.001
CFI (comparative fit index)Improvement over a model in which no variables are related0.95 or higher0.942
TLI (Tucker-Lewis index)Like the CFI, with a penalty for complexity0.95 or higher0.827
RMSEA (root mean square error of approximation)Misfit per degree of freedom0.06 or lower; up to 0.08 is acceptable; above 0.10 is poor0.166
SRMR (standardized root mean square residual)Average difference between observed and model correlations0.08 or lower0.071

Model 1 fits poorly. Its RMSEA of 0.166 is well above 0.10, its TLI is 0.827 and its CFI is just below 0.95. Only the SRMR falls inside its guide. The chi-square test also rejects it, although in a sample of this size it would reject even small departures, so it is reported but not decisive on its own. Model 2 has 0 degrees of freedom, so it is saturated, and its perfect fit indices (CFI 1, RMSEA 0, SRMR 0) carry no information about whether it is correct. No fit index shows that a model is correct; the indices describe only how well it reproduces the observed covariances.

6.3.2 Comparing Nested Models

Model 1 is nested in Model 2: fixing the two direct paths of Model 2 at zero gives Model 1. By this we mean that the smaller model is a special case of the larger one, with nothing new added, only some paths removed. Nested models fitted to the same people can be compared with a chi-square difference test, which anova(fit_full, fit_partial) reports, even when the larger model is saturated. The test asks whether the paths that the smaller model removes were doing useful work: if removing them barely worsens the fit, the simpler model is preferred, and if the fit becomes much worse, the removed paths are needed. The difference is 173.76 on 2 degrees of freedom (one for each path that Model 1 removes), with p < 2.2 × 10−16, so removing the direct paths makes the fit much worse. The Akaike information criterion (AIC), which balances fit against the number of parameters, agrees: the anova() output prints 32,864 for Model 2 and 33,033 for Model 1, and lower is better, so it favours Model 2. The BIC (32,918 and 33,076) points the same way.

In words, the data are inconsistent with a model in which support is related to depressive and anxiety symptoms only through loneliness. Section 3 explained that labels such as "full" and "partial" mediation depend mainly on sample size. With more than 3,000 people, a model with no direct paths was always likely to be rejected, so the report describes the size of each direct and indirect path with its confidence interval and does not rest on a label.

In other studies the two pieces of evidence do not always line up as neatly. A restricted model can meet the guides in Table 8.10 and still fit significantly worse than the larger model in the chi-square difference test. There is no contradiction: the fit indices say that the restricted model approximates the data well, and the comparison says that the paths it leaves out are small but detectable, which is common in large samples. In that case the larger model is usually reported, with the size of each path, so that a small direct path is shown rather than hidden. The BIC penalizes extra paths more heavily than the AIC, so when the difference in fit is small the BIC can favour the restricted model while the AIC and the chi-square difference test favour the larger one. The report then gives both models and the reason for the choice.

The comparison favours Model 2, and the next subsection reads its estimates.

6.4 Results from the Chosen Model

Activity 8.4 refits Model 2 with 1,000 bootstrap samples and reports percentile confidence intervals for every path and for the two indirect effects. It then reports the standardized coefficients, which express each path in standard deviation units, so that paths measured on different scales can be compared, and the R-squared for each endogenous variable, the proportion of its variance that the model explains. Table 8.11 collects these results for every path and for the two indirect effects.

Table 8.11. Unstandardized estimates with 95% bootstrap confidence intervals and standardized estimates from Model 2 (n = 3,099).

Path or quantityUnstandardized estimate (95% bootstrap CI)Standardized
Support → loneliness (a)−0.627 (−0.677 to −0.574)−0.403
Loneliness → depression (b1)0.365 (0.331 to 0.402)0.381
Support → depression, direct (c1)−0.329 (−0.386 to −0.273)−0.221
Loneliness → anxiety (b2)0.346 (0.310 to 0.379)0.371
Support → anxiety, direct (c2)−0.217 (−0.273 to −0.160)−0.150
Indirect, depression (a × b1)−0.229 (−0.257 to −0.203)−0.154
Indirect, anxiety (a × b2)−0.217 (−0.246 to −0.191)−0.149
Residual correlation, depression and anxiety(not shown)0.472

Both indirect associations are clearly different from zero, because their bootstrap intervals exclude zero. The indirect association for depressive symptoms (−0.229) matches the ACME from Section 3, and the indirect association for anxiety symptoms is similar in size (−0.217). The standardized coefficients are read in standard deviation units: a support score one standard deviation higher goes with loneliness about 0.40 standard deviations lower, and the paths through loneliness (−0.40, 0.38 and 0.37) are larger than the direct paths (−0.22 and −0.15). In the standardized solution each indirect path is the product of its two standardized paths, and standardizedSolution() in Activity 8.4 prints it as a defined parameter: −0.154 for depressive symptoms and −0.149 for anxiety symptoms, so a support score one standard deviation higher goes with depressive symptoms about 0.15 standard deviations lower through loneliness. Unstandardized estimates stay in each variable's original units, so a written answer says which kind of coefficient it quotes. The model explains 16% of the variance in loneliness, 26% in depressive symptoms and 20% in anxiety symptoms, so most of the variation in each comes from factors outside the model. R-squared measures variance explained, not fit. The residual correlation of 0.47 shows that depressive and anxiety symptoms remain strongly related after support and loneliness are taken into account, which justifies the covariance in the model.

Figure 8.11 brings the standardized results together in the form used in a report: the standardized coefficient on each path, the residual correlation of the two outcomes and the R-squared of each endogenous variable.

Social support Loneliness Depressive symptoms Anxiety symptoms −0.40 0.38 0.37 −0.22 −0.15 0.47 R² = 0.16 R² = 0.26 R² = 0.20
Figure 8.11. Standardized coefficients from Model 2 (CSCS 2021, n = 3,099). Black arrows are the paths through loneliness, blue arrows are the direct paths, and the purple double-headed arrow is the residual correlation of the two outcomes. All paths have 95% bootstrap confidence intervals that exclude zero. Standardized indirect associations: −0.15 for depressive symptoms and −0.15 for anxiety symptoms.

Every variable in Figure 8.11 is an observed score. The next subsection asks what changes when one of those scores is replaced by a latent variable.

6.5 From Path Analysis to Structural Equation Modelling

Every observed score contains measurement error. By this we mean that a person's loneliness score reflects not only how lonely they are but also chance factors, such as how they read a question or their mood on the day of the survey. Measurement error weakens (attenuates) correlations, because the random part of each score is unrelated to anything else and so dilutes the real relationship. A latent variable measured by several items separates the shared variation in the items from their error: what the three loneliness items have in common is treated as the underlying loneliness, and what is unique to each item is treated as error. A structural equation model joins the two ideas, so that the paths are estimated between the underlying constructs rather than between error-laden scores. Its measurement model is a confirmatory factor analysis, which defines each latent variable by its items with the =~ operator, and its structural model is a set of paths among the latent and observed variables, written with ~ exactly as in 6.2. Figure 8.12 shows such a model for the CSCS data, with a latent loneliness factor, drawn as an oval, measured by the three UCLA items in place of the observed loneliness score.

companionship left_out isolated Lonely 0.69 0.69 0.76 Social support Depressivesymptoms −0.46 0.47 −0.16 Measurementmodel (top) Structural model (paths among support, Lonely and depressive symptoms) Standardized indirect effect (lavaan defined parameter): −0.215
Figure 8.12. A structural equation model for the CSCS data (n = 3,110), with standardized estimates. The oval is a latent loneliness factor measured by the three UCLA items, which replaces the observed loneliness score of the earlier models. Each item also has a residual (its measurement error), which is not drawn.

Activity 8.4 fits every model of this section in R, from the simple mediation model of 6.2 to the model in Figure 8.12. Run it along with the text: it fits and compares Models 1 and 2, refits Model 2 with the bootstrap, prints the standardized estimates and R-squared values of Table 8.11, and ends with the structural equation model. Its questions ask you to judge fit and choose a model, interpret the indirect paths and standardized coefficients, and compare the SEM with the path model.

R Activity 8.4: path models, model comparison and a first structural equation model

Text version of the activity: the code of the run-along script, its console output and notes on reading it.

library(lavaan)              # install.packages("lavaan") once, if needed
load(url("https://raw.githubusercontent.com/jorgeandr3s/heal/main/cscs/public_data/CSCS2025_full_cleaned_deidentified_data_and_metadata.RData"))   # CSCS data, read from the web
data <- data[data$SURVEY_collection_year == 2021, ]   # the 2021 wave
path_data <- data.frame(
  support    = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  loneliness = data$LONELY_ucla_loneliness_scale_score,   # UCLA, 3 to 9
  depression = data$WELLNESS_phq_score,                   # PHQ-2, 0 to 6
  anxiety    = data$WELLNESS_gad_score)                   # GAD-2, 0 to 6
path_data <- na.omit(path_data)   # people with all four scores
nrow(path_data)
Console output
This is lavaan 0.7-3 lavaan is FREE software! Please report any bugs. [1] 3099

The file is read straight from the web (an internet connection is needed). The path models use the 3,099 people in the 2021 wave with complete data on support (MSPSS, 1 to 7), loneliness (UCLA three-item scale, 3 to 9), depressive symptoms (PHQ-2, 0 to 6) and anxiety symptoms (GAD-2, 0 to 6), eleven fewer than in Sections 2 and 3.

model_med <- '
  loneliness ~ a * support
  depression ~ b * loneliness + c * support
  indirect := a * b
  total    := c + a * b
'
fit_med <- sem(model_med, data = path_data)
summary(fit_med)
Console output
lavaan NOTE: Standard errors and confidence intervals of the (nonlinear) defined (:=) parameters are based on the first-order delta method; for strongly nonlinear definitions, se_def = "mc" (Monte Carlo) or se = "bootstrap" may be more accurate. lavaan 0.7-3 ended normally after 1 iteration Estimator ML Optimization method NLMINB Number of model parameters 5 Number of observations 3099 Model Test User Model: Test statistic 0.000 Degrees of freedom 0 Browne's residual (NT model-based) test Test statistic 0.000 Degrees of freedom 0 Parameter Estimates: Standard errors Standard Information Expected Information saturated (h1) model Structured Regressions: Estimate Std.Err z-value P(>|z|) loneliness ~ support (a) -0.627 0.026 -24.516 0.000 depression ~ loneliness (b) 0.365 0.016 22.601 0.000 support (c) -0.329 0.025 -13.097 0.000 Variances: Estimate Std.Err z-value P(>|z|) .loneliness 2.492 0.063 39.364 0.000 .depression 2.017 0.051 39.364 0.000 Defined Parameters: Estimate Std.Err z-value P(>|z|) indirect -0.229 0.014 -16.617 0.000 total -0.559 0.025 -22.482 0.000

Reading the output. Under Regressions, the labelled paths are a = −0.627, b = 0.365 and c = −0.329, which match the linear regressions of Section 3 (−0.626, 0.366 and −0.331) apart from the eleven people who are now excluded. In lavaan the label c names the direct path, which Section 3 called c′. Under Defined Parameters, the indirect effect is a × b = −0.229 (standard error 0.014) and the total effect is c + a × b = −0.559. Under Variances, the dots before .loneliness and .depression mark residual variances. Degrees of freedom 0 and a test statistic of 0.000 show that the model is saturated: it reproduces the observed covariances exactly, so its fit cannot be tested.

model_full <- '
  loneliness ~ support
  depression ~ loneliness
  anxiety    ~ loneliness
  depression ~~ anxiety
'
fit_full <- sem(model_full, data = path_data)
fitMeasures(fit_full, c("chisq", "df", "pvalue", "cfi", "tli", "rmsea", "srmr"))
Console output
chisq df pvalue cfi tli rmsea srmr 173.757 2.000 0.000 0.942 0.827 0.166 0.071

Model 1 has 2 degrees of freedom, one for each direct path it leaves out. Its chi-square is 173.8 (p printed as 0.000), its RMSEA is 0.166, its CFI is 0.942 and its TLI is 0.827: by every index except the SRMR (0.071), the model fits poorly.

model_partial <- '
  loneliness ~ a * support
  depression ~ b1 * loneliness + c1 * support
  anxiety    ~ b2 * loneliness + c2 * support
  depression ~~ anxiety
  indirect_dep := a * b1
  indirect_anx := a * b2
'
fit_partial <- sem(model_partial, data = path_data)
fitMeasures(fit_partial, c("chisq", "df", "cfi", "rmsea", "srmr"))
anova(fit_full, fit_partial)   # chi-square difference test, AIC and BIC
Console output
chisq df cfi rmsea srmr 0 0 1 0 0 Chi-Squared Difference Test Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) fit_partial 0 32864 32918 0.00 fit_full 2 33033 33076 173.76 173.76 0.16647 2 < 2.2e-16 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Model 2 has 0 degrees of freedom, so it is saturated and fits perfectly by construction. The chi-square difference is 173.76 on 2 degrees of freedom (p < 2.2 × 10−16), so removing the two direct paths makes the fit much worse. The AIC is 32,864 for Model 2 and 33,033 for Model 1, and the BIC is 32,918 and 33,076; lower values are better, so both favour Model 2.

set.seed(2021)
fit_boot <- sem(model_partial, data = path_data,
                se = "bootstrap", bootstrap = 1000)
est <- parameterEstimates(fit_boot, boot.ci.type = "perc")
est[est$op %in% c("~", ":="), c("lhs", "op", "rhs", "est", "ci.lower", "ci.upper")]
Console output
Warning message: lavaan->lav_model_nvcov_bootstrap(): 4 bootstrap runs failed or did not converge. lhs op rhs est ci.lower ci.upper 1 loneliness ~ support -0.627 -0.677 -0.574 2 depression ~ loneliness 0.365 0.331 0.402 3 depression ~ support -0.329 -0.386 -0.273 4 anxiety ~ loneliness 0.346 0.310 0.379 5 anxiety ~ support -0.217 -0.273 -0.160 11 indirect_dep := a*b1 -0.229 -0.257 -0.203 12 indirect_anx := a*b2 -0.217 -0.246 -0.191

The bootstrap refits the model 1,000 times. The warning says that 4 runs failed or did not converge; with 1,000 runs, losing a handful does not change the intervals in any meaningful way. The columns ci.lower and ci.upper are 95% percentile bootstrap intervals: the indirect association for depressive symptoms is −0.229 (−0.257 to −0.203), and for anxiety symptoms −0.217 (−0.246 to −0.191).

std <- standardizedSolution(fit_boot)
std[std$lhs != std$rhs, c("lhs", "op", "rhs", "est.std")]   # paths, covariance, indirect
lavInspect(fit_boot, "rsquare")   # variance explained
Console output
lhs op rhs est.std 1 loneliness ~ support -0.403 2 depression ~ loneliness 0.381 3 depression ~ support -0.221 4 anxiety ~ loneliness 0.371 5 anxiety ~ support -0.150 6 depression ~~ anxiety 0.472 11 indirect_dep := a*b1 -0.154 12 indirect_anx := a*b2 -0.149 loneliness depression anxiety 0.162 0.262 0.204

The est.std column gives standardized estimates: −0.403 for support to loneliness, 0.381 and 0.371 for loneliness to the two outcomes, and −0.221 and −0.150 for the direct paths. The ~~ row is the residual correlation of the outcomes (0.472), and the standardized indirect effects are −0.154 and −0.149. The R-squared values are 0.162 for loneliness, 0.262 for depressive symptoms and 0.204 for anxiety symptoms.

sem_data <- data.frame(
  companionship = data$LONELY_ucla_loneliness_scale_companionship_num,
  left_out      = data$LONELY_ucla_loneliness_scale_left_out_num,
  isolated      = data$LONELY_ucla_loneliness_scale_isolated_num,
  support       = data$PSYCH_zimet_multidimensional_social_support_scale_score,
  depression    = data$WELLNESS_phq_score)
sem_data <- na.omit(sem_data)   # people with all five scores
nrow(sem_data)
model_sem <- '
  Lonely =~ companionship + left_out + isolated
  Lonely     ~ a * support
  depression ~ b * Lonely + c * support
  indirect := a * b
'
fit_sem <- sem(model_sem, data = sem_data)
fitMeasures(fit_sem, c("chisq", "df", "cfi", "rmsea", "srmr"))
Console output
[1] 3110 chisq df cfi rmsea srmr 38.851 4.000 0.991 0.053 0.016

The three UCLA items are each scored 1 (hardly ever) to 3 (often), and 3,110 people have all five scores. The line with =~ is the measurement model (a latent Lonely factor measured by the three items), and the lines with ~ are the structural model. The model fits well (chi-square 38.9 on 4 df, CFI 0.991, RMSEA 0.053, SRMR 0.016). Question 3 asks you to print its standardized estimates and compare them with the path model.

Files for this activity Data Code Answer key

R Reflect on what you just ran

Answer each question from your own output, as on the final exam (Section 3, Option B):

1. Judge the fit of Model 1 using the fit indices and the guides taught in the course, and say what the perfect fit of Model 2 tells you. Then compare the two models: which would you report, and why? Why should the result not be summarised as "partial mediation"?

Model answerModel 1 fits poorly: its RMSEA (0.166) is far above the guide of 0.06 and above the 0.10 that marks poor fit, its TLI (0.827) is far below 0.95 and its CFI (0.942) is just below 0.95; only the SRMR (0.071) meets its guide of 0.08 or lower. The chi-square test (173.8 on 2 df, p < 0.001) also rejects it, although with 3,099 people it rejects even small departures, so it is reported but not decisive. Model 2 has 0 degrees of freedom, so it is saturated, and its perfect fit (CFI 1, RMSEA 0, SRMR 0) holds by construction and says nothing about whether it is correct. Model 1 is nested in Model 2, and removing the two direct paths makes the fit significantly worse (chi-square difference 173.76 on 2 df, p < 0.001); Model 2 also has the lower AIC (32,864 against 33,033) and BIC (32,918 against 33,076), so I would report Model 2. The label "partial mediation" depends mainly on sample size, because with 3,099 people even small direct paths are significant, so the report gives the size of each direct and indirect path with its confidence interval instead.

2. Interpret indirect_dep and indirect_anx with their bootstrap intervals, in wording suited to a single survey. Then interpret the standardized path from support to loneliness (−0.403) and the R-squared values for the two outcomes, and say why a path diagram for a report uses standardized coefficients.

Model answerThe indirect association of social support with depressive symptoms through loneliness is −0.229 PHQ-2 points per point of support (95% bootstrap CI −0.257 to −0.203), and with anxiety symptoms it is −0.217 GAD-2 points (95% CI −0.246 to −0.191). Both intervals exclude 0, so there is evidence of an indirect association with each outcome. Because every score comes from one survey, loneliness statistically accounts for part of each association; this does not show that support lowers symptoms by reducing loneliness. The standardized path of −0.403 means that a support score one standard deviation higher goes with loneliness about 0.40 standard deviations lower. The model explains about 26% of the variance in depressive symptoms and 20% in anxiety symptoms (R-squared 0.262 and 0.204), so most of the variation comes from factors outside the model. Standardized coefficients put every path on the same scale, so paths between variables measured in different units can be compared in one figure; they do not change what the design can show.

3. Run your own code: copy lines 59 and 60 to the end of your script, change fit_boot to fit_sem in the first line, and run both lines (std <- standardizedSolution(fit_sem) and std[std$lhs != std$rhs, c("lhs", "op", "rhs", "est.std")]). In model_sem, what does =~ mean, and how would Lonely be drawn in a path diagram? Compare the standardized paths through loneliness with those of the path model (−0.403 and 0.381) and explain the difference. Name one cost of the SEM and one limitation it does not remove.

Model answerThe operator =~ is read "is measured by": Lonely is a latent variable measured by companionship, left_out and isolated (standardized loadings 0.69, 0.70 and 0.76), drawn as an oval with single-headed arrows to the three items, which are rectangles, each with its own residual. In the SEM, support to Lonely is −0.457 (−0.403 in the path model) and Lonely to depressive symptoms is 0.470 (0.381); the standardized indirect effect rises from −0.154 to −0.215 and the direct path falls from −0.221 to −0.160. The observed loneliness score contains measurement error, which attenuates (weakens) its associations; the latent factor separates the variation the items share from their error, so it reduces the attenuation and more of the association is attributed to the pathway through loneliness. Costs: the SEM needs several good items for each latent variable, larger samples and more modelling decisions, and the factor is only as meaningful as the measurement model that defines it. It does not remove the limits of the design: every score was measured in one survey, so it cannot show the order of the variables in time or remove unmeasured confounding of loneliness and depressive symptoms.
Saved.

The SEM in Activity 8.4 fits well (CFI 0.991, RMSEA 0.053, SRMR 0.016), and its structural paths through loneliness are stronger than in the path model with the observed score: −0.46 compared with −0.40 for support to loneliness, and 0.47 compared with 0.38 for loneliness to depressive symptoms. The standardized indirect effect rises from −0.15 to −0.21, and the direct path from support falls from −0.22 to −0.16. The latent variable removes the attenuation caused by measurement error in the three-item score, so more of the association is attributed to the pathway through loneliness. This changes the picture in a predictable way: when the mediator is measured with error, part of its real association with the outcome is hidden, and some of what the mediator carries is wrongly credited to the direct path instead. Correcting for the error moves that share back to the indirect pathway. SEM also brings costs. It needs several good items for each latent variable, larger samples and more decisions about the model, and the latent factor is only as meaningful as the measurement model that defines it, which is why evidence of its validity matters so much. A latent variable deals with measurement error only: it cannot supply temporal order or remove unmeasured confounding, so the cross-sectional design limits the SEM in the same way as every other model in this lesson.

Whether the final model is a path model or an SEM, the last step is to report it.

7.4 Reporting a Path Model

A path model is usually reported with a figure that shows the standardized coefficients, such as Figure 8.11, a table of unstandardized estimates with confidence intervals, such as Table 8.11, the fit indices of each model compared and the result of the comparison, the indirect effects with bootstrap intervals and the R-squared values, and the software, estimator and handling of missing data. The size of each direct and indirect path is described with its interval, rather than labelling the result "full" or "partial" mediation.

A matching results sentence is: "In a path model fitted to 3,099 CSCS participants, the indirect association of social support with depressive symptoms through loneliness was −0.23 (95% bootstrap CI −0.26 to −0.20), and with anxiety symptoms it was −0.22 (95% CI −0.25 to −0.19). A model without direct paths from support to the outcomes fitted poorly (RMSEA 0.17, CFI 0.94) and significantly worse than a model with them (chi-square difference 173.8 on 2 df, p < 0.001; AIC 33,033 compared with 32,864)." The sentence describes associations, as every result from these cross-sectional data must. Good fit does not show that the arrows point the right way: when every variable comes from one survey, a model with some arrows reversed (for example, from depressive symptoms to loneliness) can fit the data equally well, so a path model shows whether a set of associations is consistent with the proposed pathways, not that the pathways are causal.

The narrated walkthrough in the red card below offers a second route through the path models of Activity 8.4.

Learn to do this in R

Narrated R walkthrough: SEM Path Analysis

The SEM Path Analysis walkthrough runs the lavaan code in this section line by line, with narration and path diagrams: the syntax, the simple mediation model, the two models with two outcomes, the model comparison, and the bootstrap, standardized and R-squared results.

Open the SEM Path Analysis walkthrough

The steps of this lesson apply beyond the CSCS. The callout below restates them as a sequence to follow when a new research question involves a possible mediator or moderator.

Applying This Lesson to a New Research Question

When a research question involves a possible mediator or moderator, the analysis starts by drawing the DAG and deciding the position of each third variable, and whether any variable is a proposed effect modifier. For moderation, the analyst fits the interaction, reports the interaction coefficient and the simple slopes, and plots one line per group. For mediation, the analyst fits the mediator and outcome models with the same covariates, estimates the indirect, direct and total effects with mediate() and a bootstrap, and runs medsens(). In either case, the results paragraph uses the language of association, and the limitations state what a cross-sectional design such as the CSCS cannot show.

This section has written the mediation model as a path model, extended it to two outcomes, compared nested models, read the chosen model, added a latent variable to form a structural equation model and set out how a path model is reported. The key takeaways and knowledge check below review this material, and the lesson closes with the final assessment.

Key Takeaways

  • 6.1 Path diagrams use a small, fixed set of symbols, so it is worth learning to read them like a map. A rectangle is an observed variable recorded in the dataset, an oval is a latent variable measured through several items, a single-headed arrow is a regression path, a double-headed arrow is a covariance with no direction assumed, and a residual is the part of a variable that the model leaves unexplained. A variable with no arrows pointing at it is exogenous (here, support), and each variable with at least one arrow pointing at it is endogenous and has its own equation and residual, so a diagram with three endogenous variables is three regressions fitted together. When you read or sketch a diagram, count the endogenous variables to see how many equations there are, and check whether the residuals of two outcomes are joined by a double-headed arrow, as depressive and anxiety symptoms are in Figure 8.10.
  • 6.2 The lavaan package writes a path model as a block of text with one relationship per line, and four operators cover everything in this lesson: ~ is read "is regressed on", ~~ "covaries with", =~ "is measured by" and := "is defined as". A label written with an asterisk in front of a predictor, as in loneliness ~ a * support, names that path, so that lines such as indirect := a * b and total := c + a * b can define the indirect and total effects inside the model. In the output, the labelled paths appear under Regressions and the defined indirect and total effects under Defined Parameters. Labels are only names, so check what each one points to: in Activity 8.4 the label c marks the direct path, which Section 3 called c′.
  • 6.3 Fit indices describe how well a model that leaves some paths out reproduces the observed covariances, and they are read together rather than one at a time. The usual guides are a chi-square p-value above 0.05 (although in large samples this test rejects almost every model), a CFI and TLI of 0.95 or higher, an RMSEA of 0.06 or lower (up to 0.08 acceptable, above 0.10 poor) and an SRMR of 0.08 or lower; Model 1, with an RMSEA of 0.166 and a TLI of 0.827, fits poorly even though its SRMR of 0.071 meets its guide. A saturated model with 0 degrees of freedom fits perfectly by construction, so its CFI of 1 and RMSEA of 0 say nothing about whether it is correct. Nested models fitted to the same people are compared with a chi-square difference test, whose degrees of freedom equal the number of paths removed, and with the AIC, where lower is better; here both favour Model 2 with the direct paths. If a restricted model meets the guides but fits significantly worse, or the BIC disagrees with the AIC, explain that the omitted paths are small but detectable and report the larger model with the size of each path.
  • 6.4 Once a model is chosen, read it through three kinds of output. The indirect paths come with bootstrap confidence intervals, −0.23 (95% CI −0.26 to −0.20) for depressive symptoms and −0.22 (95% CI −0.25 to −0.19) for anxiety symptoms, and an interval that excludes zero shows that the indirect association is clearly different from zero. Standardized coefficients express every path in standard deviation units, so you can compare paths measured on different scales (for example −0.40 from support to loneliness against −0.15 for the direct path to anxiety), while unstandardized estimates stay in each variable's original units. The R-squared for each endogenous variable is the share of its variance that the model explains: 16% for loneliness, 26% for depressive symptoms and 20% for anxiety symptoms. In a written answer, give the estimate with its interval and say whether you are quoting a standardized or an unstandardized coefficient.
  • 6.5 A structural equation model adds a measurement model to a path model: each latent variable is defined by several items with =~, as in confirmatory factor analysis, and the structural paths are written with ~ exactly as before. Because the latent variable separates the shared variation in the items from their measurement error, it reduces the attenuation that error causes, so the paths through loneliness become stronger (a standardized indirect effect of −0.21 in the SEM against −0.15 with the observed score). The costs are real: SEM needs several good items for each latent variable, larger samples and more modelling decisions, and a latent factor is only as meaningful as the measurement model that defines it. For exam answers, the key point is that a latent variable deals with measurement error only; it does not supply temporal order or remove unmeasured confounding, so a cross-sectional SEM is limited in the same way as every other model in the lesson.
  • 7.4 A path model is reported with a figure of standardized coefficients, a table of unstandardized estimates with confidence intervals, the fit indices of each model compared and the result of the comparison, the indirect effects with bootstrap intervals and the R-squared values, together with the software, estimator and handling of missing data. Describe the size of each direct and indirect path rather than labelling the result "full" or "partial" mediation, since those labels mostly reflect sample size. Keep the language associational, and remember that good fit does not show that the arrows point the right way: when every variable comes from one survey, a model with some arrows reversed (for example from depressive symptoms to loneliness) can fit the data equally well. A sound closing sentence says that the pattern of associations is consistent with the proposed pathways, not that the pathways are causal.
Knowledge check: this section

1. A path model is written in lavaan as shown below. Which description of its path diagram is correct?

stress  ~ a * noise
sleep   ~ b1 * stress + c1 * noise
fatigue ~ b2 * stress
sleep  ~~ fatigue
ind_sleep := a * b1
An oval represents a latent variable, which lavaan defines with =~. All four variables here are observed scores in ~ regression lines, so they are rectangles, and stress is a predictor of sleep and fatigue, not a factor measured by them.
In lavaan, ~ means "is regressed on", so the outcome is on the left and each predictor on the right sends an arrow to it. Reading the left-hand variable as the predictor reverses every arrow.
Each ~ line gives single-headed arrows from the predictors on the right to the outcome on the left, the ~~ line is a covariance drawn as a double-headed arrow between residuals, and := defines a quantity that is reported but not drawn.
The ~~ operator is a covariance, drawn as a double-headed arrow, not a regression path. The := line defines a new quantity from labelled paths, which is reported but not drawn as an arrow.
The correct description has four rectangles, four single-headed arrows, one double-headed arrow and a defined indirect effect. In lavaan, ~ means "is regressed on", so the outcome is on the left and each predictor on the right sends a single-headed arrow to it: noise → stress, stress → sleep, noise → sleep and stress → fatigue. The ~~ line is a covariance, drawn as a double-headed arrow, here between the residuals of sleep and fatigue, so that their unexplained parts can be correlated. The labels a and b1 name two paths, and := defines a new quantity from them (the indirect effect of noise on sleep through stress), which is reported with the other estimates but not drawn. All four variables are observed scores, so they are rectangles; an oval would need a measurement line written with =~. The second option is the common error of reading the left-hand variable as the predictor. (Section 4, 6.1 Path Diagrams and Table 8.8; 6.2.1 Operators and Labels and Table 8.9; Objectives 6.1 and 6.2)

2. A path model of 1,600 adults links job strain to sleep problems through stress. The reporting figure gives standardized coefficients of 0.40 for strain → stress, 0.35 for stress → sleep problems and 0.12 for the direct path strain → sleep problems, with R-squared values of 0.16 for stress and 0.20 for sleep problems. The standardized solution in R also lists the defined indirect path (ind := a*b) as 0.14. Which reading is correct?

Standardized coefficients put every path in standard deviation units, so paths can be compared across variables on different scales. The standardized indirect path is the product of the paths through stress, and R-squared is the share of variance in sleep problems the model explains.
A standardized coefficient is a difference in standard deviations, not a percentage of a variable that is caused. Path coefficients in survey data also describe associations, not shares of causation.
R-squared is the share of the variance in sleep problems that the model explains, not a share of people. It says nothing about how many adults have sleep problems or why.
R-squared is not a fit index, and the 0.95 guide applies to the CFI and TLI. A model can explain a modest share of variance and still fit well.
The correct reading compares paths in standard deviation units and reads R-squared as variance explained. Standardized coefficients put every path on the scale of standard deviations, so paths between variables measured on different scales can be compared: among people with the same strain, a stress score one standard deviation higher goes with sleep problems 0.35 standard deviations higher, much larger than the direct path of 0.12, and the standardized indirect path that R prints (0.14) is the product of the two standardized paths through stress. An R-squared is the share of an endogenous variable's variance that the model explains, so the model explains 20% of the variation in sleep problems and leaves 80% unexplained. R-squared is not a fit index, which is why the last option is wrong, and neither number is a share of people or of causes. (Section 4, 6.4 Results from the Chosen Model, Table 8.11 and Figure 8.11; Objective 6.4)

3. A path model with two outcomes and no direct paths from the exposure (2 df) is fitted to 2,200 people. Using the output below and the guides taught in this section, how well does it fit?

chisqdfpvaluecfitlirmseasrmr
24.802< 0.0010.9850.9550.0720.021
In large samples the chi-square test rejects almost every model that leaves something out, so a significant result is expected with 2,200 people. Fit is judged from the indices read together.
The CFI, TLI and SRMR meet their guides, and the RMSEA is above 0.06 but below 0.08, which counts as acceptable. Read together, the indices show acceptable fit, and the significant chi-square is expected in a sample this large.
An RMSEA between 0.06 and 0.08 counts as acceptable, and it is well below the 0.10 that marks poor fit. One index slightly above its good-fit guide does not require rejection when the others meet theirs.
No index shows that a model is correct; the indices describe how well it reproduces the observed covariances. The fit is acceptable, not perfect, since the RMSEA is above its good-fit guide.
The correct judgement is acceptable fit, from the indices read together. Compare each index with its guide: the CFI (0.985) and TLI (0.955) are at or above 0.95, and the SRMR (0.021) is below 0.08, so these meet the guides for good fit. The RMSEA of 0.072 is a little above the 0.06 guide but below 0.08, which counts as acceptable, and well below the 0.10 that marks poor fit. The chi-square test (24.8 on 2 df, p < 0.001) rejects the model, but in large samples it rejects almost every model that leaves something out, so it is read alongside the indices rather than alone, which is why the first option is wrong. No index shows that a model is correct: the indices describe how well it reproduces the observed covariances. (Section 4, 6.3.1 Reading the Fit Indices and Table 8.10; Objective 6.3)

4. The model in question 3 (Model 1, no direct paths) is compared with Model 2, which adds a direct path from the exposure to each outcome and is saturated (0 df). Using the output below, which conclusion and report are appropriate?

ModelDfAICBICChisq diffDf diffPr(>Chisq)
Model 2025,41025,467
Model 1225,43125,47624.802< 0.001
Acceptable fit says that Model 1 approximates the data, but the comparison shows that removing the direct paths makes the fit significantly worse. "Full mediation" is a label that depends mainly on sample size, and here the comparison contradicts it.
A saturated model's own perfect fit carries no information, but it can still serve as the larger model in a comparison. Model 1 is nested in Model 2, so a chi-square difference test applies.
Fewer paths do not guarantee a lower AIC; the AIC balances fit against the number of parameters. Here both the AIC and the BIC are lower for Model 2.
Model 1 is Model 2 with the direct paths fixed at zero, so the difference test applies, and it shows that dropping them worsens fit; the AIC and BIC agree. The report gives each path's size with its interval rather than a label.
The correct conclusion is to report Model 2 with the size of each path. Model 1 is nested in Model 2 (it is Model 2 with the two direct paths fixed at zero), so a chi-square difference test compares them: 24.8 on 2 df, p < 0.001, so removing the direct paths makes the fit significantly worse. The AIC (25,410 against 25,431) and the BIC (25,467 against 25,476) are both lower for Model 2, and lower is better. This does not contradict the acceptable fit of Model 1: its indices say that it approximates the data, and the comparison says that the paths it leaves out are small but detectable in 2,200 people. A saturated model's own perfect fit carries no information, but it can still serve as the larger model in the comparison. The first option is tempting, but "full mediation" is a label that depends mainly on sample size, and here the comparison contradicts it. (Section 4, 6.3.2 Comparing Nested Models and Activity 8.4, question 1; 7.4 Reporting a Path Model; Objectives 6.3 and 7.4)

5. In a path model, sleep quality is a single self-reported score that contains measurement error. A researcher replaces it with a latent sleep factor measured by four questionnaire items, in a structural equation model fitted to the same survey. Which statement is correct?

A latent factor separates the variation its items share from their measurement error, so the attenuation in a single observed score is reduced and paths through sleep are usually stronger. It needs good items and a larger sample, and it cannot supply temporal order or remove confounding.
A latent variable reduces the effect of measurement error, but it does nothing about temporal order or unmeasured confounding. Fitted to the same survey, the indirect effect remains associational.
Adding a latent factor does not guarantee better fit: the model must also reproduce the covariances among the items, and the factor is only as meaningful as its measurement model. More parameters do not by themselves make a model better.
This reverses the effect. Combining items in a latent factor separates their shared variation from their error rather than adding errors, so the attenuation is reduced and paths usually become stronger.
The correct statement describes what a latent variable adds and what it cannot fix. A structural equation model joins a measurement model, in which the latent factor is defined by its items with =~, to the structural paths. The factor separates the variation the items share from their measurement error, so the attenuation that error causes in a single observed score is reduced and the paths through sleep are usually stronger; in the CSCS, the paths through loneliness rose from −0.40 to −0.46 and from 0.38 to 0.47. It needs several good items, a larger sample and more modelling decisions, and the factor is only as meaningful as its measurement model. Because it uses the same survey, it cannot establish the order of the variables in time or remove unmeasured confounding, which is why the second option is wrong. (Section 4, 6.5 From Path Analysis to Structural Equation Modelling, Figure 8.12, Activity 8.4, question 3, and the paragraph after the activity; Objective 6.5)

6. A survey of 2,200 schoolteachers, completed once, was analysed with a path model in which weekly working hours (work10, hours divided by 10) are linked to job satisfaction (0 to 10) through emotional exhaustion, with a direct path c2 from working hours to satisfaction. With 1,000 bootstrap samples, lavaan gives the estimates below. A colleague writes: "Exhaustion fully mediates the association between working hours and job satisfaction, because c2 is not significant." Which response is best?

ParameterEstimate95% bootstrap CI
Direct path, work10 → satisfaction (c2)−0.03−0.10 to 0.04
Indirect path through exhaustion (ind_sat := a*b2)−0.36−0.44 to −0.29
An interval that includes zero shows imprecision, not absence: the c2 interval still allows a small direct association. "Full mediation" rests on significance, which depends mainly on sample size and precision, so it is not the main result.
Every measure came from one survey, so causal wording such as "lower" and "by causing" is not supported. The full mediation label is also not recommended, since it describes power more than the pathway.
The labels depend mainly on sample size and precision, and the c2 interval does not rule out a small direct association. Reporting the indirect and direct associations with their intervals, in associational wording, describes the result directly.
The indirect association has its own interval, which excludes zero, so the result for the direct path c2 says nothing about it. The two parts are judged separately.
The best response replaces the label with the size of each path. Whether a direct path reaches significance depends mainly on the sample size and the precision of the estimate, so "full" and "partial" describe statistical power more than the pathway. Here the direct path is −0.03, but its interval (−0.10 to 0.04) includes direct associations as large as −0.10, so a small direct association is not ruled out; an interval that includes zero shows imprecision, not absence (the first option). The indirect association has its own interval, which excludes zero, so the result for c2 says nothing about it (the last option). Because every measure came from one survey, causal wording such as "lower" and "by causing" is not supported (the second option). (Section 3, 4.3 The Limits of the Baron and Kenny Causal Steps; Section 4, 6.3.2 Comparing Nested Models and 7.4 Reporting a Path Model; Objectives 6.4 and 7.4)
● Complete the quiz to continue.
Final Assessment

Lesson 8: Final Assessment

16 questions • 100% required to pass

Bringing It All Together

This lesson took two questions from a community connector program and answered them with the 2021 wave of the Canadian Social Connection Survey. Section 1 used directed acyclic graphs to separate three positions a third variable can take, and it treated effect modification as a separate question that a standard DAG does not encode. A confounder is adjusted for, a mediator is used to split an association into direct and indirect parts, a collider is left out of the model and the sampling, and an effect modifier is examined with an interaction. The section defined the total, direct and indirect effects and set out the conditions for a causal reading of an indirect effect: temporal order and no unmeasured confounding, including confounding of the mediator and the outcome. Because the survey measured every variable at the same time, every mediation result in the lesson was described as a statistical decomposition.

Section 2 found that the association between social support and loneliness was stronger among adults aged 50 and over (slope −0.81) than among younger adults (slope −0.50), and showed how centring and simple slopes make an interaction model readable. Section 3 estimated the paths of the mediation model one regression at a time, showed that a × b and c − c′ give the same indirect effect (−0.229), explained why the Baron and Kenny steps are no longer used as a test, and used mediate() to obtain a bootstrap interval: loneliness statistically accounted for about 41% of the association between support and depressive symptoms (95% CI 36% to 46%), and a sensitivity analysis showed that confounding inducing a residual correlation of about 0.4 would remove it. Section 4 wrote the model in lavaan, extended it to depressive and anxiety symptoms, preferred a model with direct paths on the chi-square difference test and the AIC, reported it with bootstrap intervals and standardized coefficients, and added a latent loneliness factor to show a structural equation model.

The same steps apply to any question about a third variable: draw the DAG and decide the role, fit the model that the role calls for, estimate effects with confidence intervals, check the assumptions that the data cannot confirm, and write the results in language that matches the design. The final assessment asks for these steps to be applied to new examples.

Key Takeaways from this lesson

  1. You can now place a third variable on a DAG drawn from subject knowledge: a confounder is adjusted for, a mediator is used to split the association and is left out of a total-effect model, and a collider is left out of both the model and the sampling. You can also explain why effect modification is a separate question about the size of an association, shown by a note or a diagram drawn within each group and analysed with an interaction. For the exam, settle the direction of the arrow between the exposure and the third variable from timing and mechanism, and look closely at how people entered the sample, because selection on a collider is the most common hidden trap.
  2. You can now split a total effect into its direct and indirect parts, knowing that c = c′ + a × b holds exactly in linear models fitted to the same people, and you can list the conditions for reading the indirect part causally. The reminder to carry into the exam is that randomizing the exposure does not randomize the mediator, so mediator-outcome confounding can remain even in a trial, and cross-sectional data cannot establish temporal order at all.
  3. You can now read a regression model with an interaction term: the interaction coefficient is the difference between slopes, the slope in the other group is β1 + β3, each main effect is a slope or difference at zero on the other variable, and centring and simple slopes make the results readable. Before interpreting any coefficient, check which group is the reference and where zero falls on each variable, and always state whether an interaction is on the additive or the multiplicative scale.
  4. You can now take paths a, b, c and c′ from three regressions, obtain the indirect effect in R as a × b (equal to c − c′ in linear models), and judge it by its bootstrap confidence interval from mediate(), reading the proportion mediated with caution. When a question rests on the Baron and Kenny steps or on a "full" or "partial" label, critique the label, because it mostly reflects sample size, and report the size of the effects with their intervals instead.
  5. You can now interpret the ρ reported by medsens() as the residual correlation that unmeasured mediator-outcome confounding would need to induce to remove the indirect effect. On the exam, state what ρ means, name a plausible confounder of the mediator and the outcome, and judge robustness from its size: the closer ρ is to zero (about 0.15 or 0.25), the more fragile the result, while about 0.4 needs a fairly strong confounder, and neither value says anything about temporal order.
  6. You can now read a path diagram and its lavaan syntax, judge a model's fit from the chi-square test and the CFI, TLI, RMSEA and SRMR read together, compare nested models with a chi-square difference test and the AIC, and interpret indirect paths, standardized coefficients and R-squared values. Remember that a saturated model's perfect fit carries no information, and that adding latent variables in a structural equation model reduces the attenuation caused by measurement error but does not fix temporal order or unmeasured confounding.
  7. You can now report moderation and mediation results with estimates, confidence intervals and a figure, in wording that matches what the design can show. The most useful exam habit is to check every verb: with cross-sectional data, write "was associated with" or "statistically accounted for", describe a mediation result as a statistical decomposition rather than a causal pathway, and end with what a longitudinal design would add.

The final assessment covers all four sections. All 16 questions must be answered correctly (100%) to finish the lesson.

Final Knowledge Assessment

Final assessment: the 16 questions

1. A team studying physical activity and systolic blood pressure (bp) has three questions: (i) Is activity associated with bp once sex is held constant? (ii) Does the activity slope differ between women and men? (iii) How much of the association between activity and bp runs through body weight? Which set of models answers the three questions?

Each question gets its own model: a covariate for the confounding question, a product term for the moderation question, and a mediator model plus an outcome model for the mediation question, which give paths a, b, c and c′.
This swaps the first two models. A covariate answers whether activity is associated with bp holding sex constant, and the interaction answers whether the slopes differ. A single model adjusted for weight gives only the direct effect, not the indirect one.
Including sex as a covariate fits one slope for everyone, so it cannot test whether the slopes differ. An interaction with weight asks whether weight modifies the association, not how much runs through it.
The sex coefficient tests a difference in bp between women and men, not a difference in slopes. The activity coefficient after adjusting for weight is the direct effect c′, not the indirect effect.
The correct set uses a covariate for (i), an interaction for (ii) and a mediation analysis for (iii). Question (i) is a confounding question, answered by adding sex as a covariate, which gives one activity slope adjusted for sex. Question (ii) is a moderation question, which needs the product term (activity * sex) whose coefficient is the difference between the two slopes; adjusting for sex, or reading the p-value of the sex coefficient, does not test it. Question (iii) is a mediation question: the mediator model gives path a, the outcome model with activity and weight gives b and the direct effect c′, and the indirect effect is a × b (the activity coefficient after adjusting for weight is c′, not the indirect effect). The tempting third option treats "sex is in the model" as a test of moderation, which is the error that the callout in 3.1 of Section 2 warns against. (Section 1, 1.2 Effect Modification as a Separate Question and Table 8.1; Section 2, 3.1 Moderation as a Research Question, Table 8.3 and its callout; Objectives 1.1 and 3.1)

2. A study asks whether living near a major road (X) is associated with asthma symptoms in children (Y). The DAG has these arrows: household income → living near a major road and income → asthma symptoms; living near a major road → traffic pollution at home → asthma symptoms; and living near a major road → agreed to a home visit ← asthma symptoms. Only families who agreed to the home visit are in the data. The team also asks whether the association is stronger in children under 5 than in older children. Which classification is correct?

This swaps the first two roles: income causes both exposure and outcome, so it is a confounder, and traffic pollution lies on the pathway, so it is a mediator. Whether the association is stronger in younger children concerns its size, which an arrow cannot show.
Traffic pollution is caused by living near a road, so it is a mediator, not a confounder. The home visit is a collider, and adjusting for age fits one common slope, so it does not test whether the association differs by age.
Income causes both exposure and outcome, pollution lies on the pathway and the home visit receives arrows from both, so the roles are confounder, mediator and collider. The age question concerns the size of the association, which needs an interaction or within-group estimates.
Income sends arrows into both the exposure and the outcome, which makes it a confounder, not a collider. The home visit is a common effect and so a collider, and age is a proposed effect modifier, not a mediator.
The correct classification is confounder, mediator, collider and effect modifier. Income has arrows into both the exposure and the outcome (X ← C → Y), so it is a confounder and is adjusted for. Traffic pollution at home is caused by living near a road and affects symptoms (X → M → Y), so it is a mediator, left out of a total-effect model and used to split the association. Agreeing to the home visit is affected by both the exposure and the outcome (X → Z ← Y), so it is a collider; because only families who agreed are in the data, the sample is selected on it, which can create or distort an association that no adjustment removes. Whether the association is stronger in younger children is a question about its size, which a DAG arrow does not show, so it is analysed with an exposure × age group interaction or within each age group. The second option is tempting because traffic pollution is strongly related to both variables, but its arrow comes from the exposure, which makes it a mediator. (Section 1, 1.1 Classifying a Third Variable with a DAG, the callout "Mediator or Confounder" and the paragraph on colliders in how people come to be in the data; 1.2 Effect Modification as a Separate Question and Table 8.1; Objectives 1.1 and 1.2)

3. A randomized trial assigns adults to a walking program. Fitness is measured at three months and blood pressure at six months. Diet quality affects both fitness and blood pressure, and it was not measured. Which condition for a causal reading of the indirect effect through fitness does diet threaten, and does the randomization deal with it?

Diet does not threaten temporal order; the measurement times already give the order. It affects both fitness and blood pressure, which makes it a mediator-outcome confounder.
Diet affects both the mediator and the outcome and was not measured, so it is an unmeasured mediator-outcome confounder. Fitness is not assigned at random, so randomizing the program does not remove this bias in path b.
Diet does not affect who is assigned to the program, so it is not an exposure-outcome confounder, and randomization handles that condition anyway. Adjusting for fitness, the mediator, would not remove confounding by diet.
Randomization does remove exposure-mediator confounding, but diet does not affect who receives the program. Its arrows run into fitness and blood pressure, making it a mediator-outcome confounder.
The threatened condition is no unmeasured confounding of the mediator and the outcome. Diet has arrows into fitness (the mediator) and into blood pressure (the outcome), so it is a common cause of the mediator and the outcome, and because it was not measured it cannot be adjusted for. Randomization balances the causes of who joins the walking program, so it handles exposure-outcome and exposure-mediator confounding, and the measurement times give temporal order; but fitness is not assigned at random, so diet can still bias path b and the direct and indirect effects. The last option is tempting because randomization does remove exposure-mediator confounding, but diet does not affect who is assigned to the program. (Section 1, 2.2 Conditions for a Causal Reading of an Indirect Effect, accordion panel 4 and the paragraph after it; Objective 2.2)

4. A fatigue score is regressed on weekly hours of unpaid caregiving with an interaction with employment (reference group: not employed), adjusting for age. Using the output below, which statement is correct?

TermEstimatep-value
caregiving0.15< 0.001
employedYes0.800.04
age0.020.01
caregiving:employedYes0.100.21
> c(not_employed = coef(m)[["caregiving"]],
+   employed = coef(m)[["caregiving"]] + coef(m)[["caregiving:employedYes"]])
not_employed     employed
        0.15         0.25 
The 0.10 is the interaction coefficient, the difference between the two slopes, not the slope among employed people. The employed slope that R prints is the reference slope plus this difference, so it is larger, not smaller.
The employedYes coefficient compares the groups at zero hours of caregiving, so it does not test moderation. The test of whether the slopes differ is the interaction coefficient.
The slope is read correctly, but the interaction's p-value of 0.21 is above 0.05, so the data do not show clearly that the slopes differ. A difference of this size could arise from sampling variation.
The caregiving coefficient is the slope for the reference group, and R prints the slope for employed people. The interaction is the test of moderation, and with p = 0.21 there is no clear evidence that the slopes differ.
The correct statement gives both slopes and reads the interaction's p-value correctly. The caregiving coefficient (0.15) is the slope in the reference group, people who are not employed, and the slope among employed people, which R prints, is 0.15 + 0.10 = 0.25 fatigue points per hour, holding age constant. The test of moderation is the interaction coefficient, and its p-value of 0.21 is above 0.05, so the data do not show clearly that the slopes differ: a gap of 0.10 could arise from sampling variation. The third option has the right slope but treats a difference with p = 0.21 as significant; the second reads the group coefficient, which compares the groups at 0 hours of caregiving, as a test of moderation. (Section 2, 3.2 Fitting and Interpreting an Interaction Model, Eq 8.2 and Table 8.4; Objective 3.2)

5. Systolic blood pressure is regressed on sodium intake (grams per day) with age as a continuous moderator, after centring age at 50 years and sodium at its mean. The sodium_c coefficient is 1.20 and the sodium_c:age_c coefficient is 0.04 per year. R prints the simple slopes of sodium at ages 50 and 70. What does the value printed for age 70 mean, and what does the 1.20 describe?

> slopes <- b["sodium_c"] + b["sodium_c:age_c"] * (c(50, 70) - 50)
> names(slopes) <- paste("age", c(50, 70))
> round(slopes, 2)
age 50 age 70
   1.2    2.0 
With age centred at 50, the sodium_c coefficient is the sodium slope at age 50, and the simple slope at 70 adds the interaction scaled by the distance from 50. The value R prints for age 70 is that slope, in mmHg per gram.
The value for age 70 is read correctly, but centring moved the zero point of age to 50. The sodium_c coefficient is therefore the slope at age 50, not at age 0.
Centring changes what the main effect describes but leaves the interaction unchanged. The slope still differs with age, which is why R prints different simple slopes at 50 and 70.
With an interaction, the sodium_c coefficient is the slope where age_c is zero, age 50, not an average across ages. The printed value for age 70 is a slope, not a difference in blood pressure between age groups.
The correct answer reads 2.0 as the sodium slope at age 70 and 1.20 as the slope at age 50. After centring, zero on age_c means age 50, so the sodium_c coefficient is the sodium slope at age 50. The code adds the interaction times the distance from the centring value, 1.20 + 0.04 × (70 − 50) = 2.00, so among 70-year-olds each additional gram of sodium per day goes with systolic blood pressure about 2 mmHg higher. The second option forgets the centring, and the last reads a slope as a difference between age groups. Centring changes what the main effect describes but leaves the interaction unchanged, so the slope still differs with age (the third option). In a single survey, these slopes compare people of different ages and do not show how the association changes as a person grows older. (Section 2, 3.3.2 Centring a Continuous Moderator and Table 8.5; 3.4 Simple Slopes at Chosen Values of the Moderator, Eq 8.3 and Activity 8.2; Objectives 3.3 and 3.4)

6. The table below gives the risk of an outcome with and without an exposure in two groups, and R computed the risk difference and the risk ratio in each group. A logistic regression finds a significant exposure × group interaction, and a colleague concludes that the exposure matters more in group A. Which response is best?

GroupRisk without exposureRisk with exposure
Group A5%10%
Group B20%25%
> rk$risk_diff  <- rk$risk_exposed - rk$risk_unexposed
> rk$risk_ratio <- rk$risk_exposed / rk$risk_unexposed
> rk
  group risk_unexposed risk_exposed risk_diff risk_ratio
1     A           0.05         0.10      0.05       2.00
2     B           0.20         0.25      0.05       1.25
The exposure raising risk in both groups does not rule out interaction. The risk ratios differ between groups, so there is interaction on the multiplicative scale.
A logistic interaction term compares odds ratios, so it speaks only to the multiplicative scale. The risk differences are equal here, so there is no interaction on the additive scale.
The risk ratio differs between groups but the risk difference does not, so there is multiplicative but no additive interaction. The additive scale shows that removing the exposure would prevent about the same number of cases per 100 people in each group.
Higher baseline risks in group B do not make the exposure matter more there. The risk difference is the same in both groups, and the risk ratio is larger in group A.
The correct response separates the two scales. The R output gives a risk difference of 0.05 (5 percentage points) in both groups, and a risk ratio of 2.00 in group A and 1.25 in group B. The ratios differ, so there is interaction on the multiplicative scale, which is the scale of a logistic interaction term (it compares odds ratios). The risk differences are equal, so there is no interaction on the additive scale, and removing the exposure would prevent about 5 cases per 100 people in either group (if the association were causal), which is the comparison that matters for deciding where to intervene. The second option is tempting, but a significant logistic interaction speaks only to the multiplicative scale. (Section 2, 3.5 Additive and Multiplicative Scales and Table 8.6; Objective 3.5)

7. A linear mediation analysis is fitted to the same people, with c = 1.20, a = 0.60, b = 0.80 and c′ = 0.72. R computes the indirect effect by both methods and its share of the total. Which interpretation is correct?

> a * b                  # product of coefficients
[1] 0.48
> c_total - c_direct     # difference method
[1] 0.48
> (a * b) / c_total      # share of the total
[1] 0.4
The indirect effect is right, but the printed share divides it by the total effect, not the direct effect. The proportion mediated is a share of the total association.
Both methods give the same indirect effect because the models are linear and fitted to the same people. The last line divides the indirect effect by the total, so the mediator statistically accounts for about 40% of the total association.
The printed share is the indirect effect divided by the total, so it is the part that does run through the mediator. The direct effect makes up the remaining 60%.
In linear models fitted to the same people, the total equals the direct effect plus the product of a and b exactly, so the agreement is not chance. Both methods estimate the same indirect effect.
The correct interpretation reads the printed values. Both methods give 0.48 because the models are linear and fitted to the same people, so c = c′ + a × b holds exactly and the agreement is not chance (the last option). The last line divides the indirect effect by the total effect, which is the proportion mediated, so the mediator statistically accounts for about 40% of the total association, and the direct effect (0.72) makes up the remaining 60%. Reading 0.4 as a share of the direct effect (the first option) or as the part that does not run through the mediator (the third option) mistakes what the denominator and the numerator are. (Section 1, 2.1 Total, Direct and Indirect Effects and Eq 8.1; Section 3, 4.2 Product-of-Coefficients and Difference Methods, Eq 8.4, and 4.4.2 The Proportion Mediated, Read with Caution; Objectives 2.1, 4.2 and 4.4)

8. A pilot study of 90 people finds an indirect effect of 0.30 (95% bootstrap CI 0.08 to 0.55) and a direct effect c′ of 0.25 (95% CI −0.05 to 0.55, p = 0.10). The authors conclude that the mediator "fully mediates" the association. Why is this conclusion weak?

No definition of full mediation requires the indirect effect to be non-significant; the causal steps call it full when the direct effect is non-significant. The problem is that such a label depends mainly on sample size.
The bootstrap resamples the data with replacement, and its interval for the indirect effect is not the problem. The weakness of the conclusion lies in reading a non-significant direct effect in a small sample as no direct effect.
This repeats the Baron and Kenny reasoning that the lesson no longer recommends. A non-significant direct effect in 90 people mostly reflects low power, and its interval allows a sizeable direct effect.
In a small sample a sizeable direct effect can miss significance, so the label describes power more than the pathway. The interval for c′ allows a direct effect larger than the indirect one, so both parts should be reported with intervals.
The correct answer is that the label mistakes imprecision for absence. Whether c′ is significant depends largely on the sample size, and in 90 people even a sizeable direct effect can miss significance. Here c′ is 0.25, almost as large as the indirect effect, and its interval runs up to 0.55, so the data are consistent with a direct effect larger than the indirect one. The labels "full" and "partial" describe statistical power more than the pathway, so the report should give the size of both parts with their intervals. The third option repeats the Baron and Kenny reasoning that the lesson explains is no longer recommended. (Section 3, 4.3 The Limits of the Baron and Kenny Causal Steps, panel "Full and partial labels depend on sample size" and the paragraph after the accordion; Objective 4.3)

9. In a path model, the lavaan output for the defined indirect effect (indirect := a*b) gives an estimate of 0.04 with a 95% bootstrap confidence interval from −0.01 to 0.09. What should be concluded?

A point estimate above zero is not evidence on its own. The interval includes zero, so the data are consistent with no indirect association.
The estimate is in units of the outcome per unit of the exposure, not a percentage. A share of the total would come from dividing the indirect effect by the total effect.
The 95% interval includes zero as well as small positive values, so there is no clear evidence of an indirect association, and a small one is not ruled out.
An interval that includes zero shows imprecision, not absence. It also includes small positive values, and a larger study could detect a small indirect association.
The correct conclusion is that there is no clear evidence of an indirect association. The information needed is whether the 95% interval includes 0: it runs from −0.01 to 0.09, so zero is a plausible value, as are small positive values up to 0.09. A point estimate above zero (the first option) is not evidence on its own, because the interval shows how much the estimate could vary from sample to sample. The interval also does not prove that the pathway is absent (the last option), since a larger study could detect a small indirect association. The estimate 0.04 is in units of the outcome per unit of the exposure, not a percentage. (Section 3, 4.4.1 Bootstrap Confidence Intervals for the Indirect Effect and Activity 8.3; Section 4, 6.4 Results from the Chosen Model and Table 8.11; Objectives 4.4 and 6.4)

10. A mediate() analysis reports ACME 0.20 (95% CI 0.12 to 0.28), ADE −0.15 (95% CI −0.27 to −0.03), Total Effect 0.05 (95% CI −0.07 to 0.17) and Prop. Mediated 4.00. Why can the proportion mediated not be read as a share?

The direct and indirect parts have opposite signs and nearly cancel, so the total is small and the ratio exceeds 1, with no sensible reading as a share. This is inconsistent mediation, and the two parts are reported separately.
A proportion above 1 follows from dividing by a small total when the parts have opposite signs, not from a failed bootstrap. Rerunning the bootstrap would not change the reason.
When the direct and indirect parts have opposite signs, the indirect effect can exceed the total, which is inconsistent mediation. That pattern is a real feature of the data, not an error.
The proportion mediated is not limited to binary outcomes. The problem here is that the total is close to zero because the two parts point in opposite directions.
The correct answer is that opposite signs make the ratio meaningless as a share. The total effect (0.05) is the sum of the two parts, and the proportion mediated that mediate() prints (4.00) is the ACME divided by that small total. Because the direct and indirect parts point in opposite directions, they nearly cancel, the total is small and its interval includes zero, and the ratio exceeds 1, a value with no sensible reading as a share. This pattern is inconsistent mediation, and the report gives the indirect and direct associations separately with their intervals. The second option is tempting, but a proportion above 1 follows from the arithmetic, not from a failed bootstrap. (Section 3, 4.4.2 The Proportion Mediated, Read with Caution and the 4.3 accordion panel "Inconsistent mediation is ruled out"; Objective 4.4)

11. A single survey of 3,000 adults is analysed with a path model in which financial strain is linked to sleep problems and to fatigue through stress. The model, which leaves out some paths, fits well (CFI 0.99, RMSEA 0.03), and the indirect association of strain with sleep problems through stress is 0.10 (95% bootstrap CI 0.06 to 0.14). Which sentence suits the report?

Good fit means the model reproduces the observed covariances, but with all measures from one survey a model with some arrows reversed can fit equally well. Fit cannot confirm a causal pathway, and "worsened" is causal wording.
The sentence describes the indirect association with its interval in associational wording, and it adds that one survey cannot fix the direction of the arrows, since a model with some arrows reversed could fit as well.
Fit describes how well a model reproduces the observed covariances, not the direction of its arrows. In cross-sectional data, models with some arrows reversed can fit equally well.
"Full mediation" is a label the lesson advises against, and good fit does not show that the arrows point in the right direction or that no direct path exists. The result is reported as the size of each path with its interval.
The correct sentence uses associational wording and adds the design caution. Good fit means that the model reproduces the observed covariances well, but when every variable comes from one survey, a model with some arrows reversed (for example, sleep problems → stress) can fit the data equally well, so fit cannot show the direction of the arrows. The indirect association is therefore described as the part of the association that stress statistically accounts for, with its interval. The first and third options treat good fit as proof of a causal direction, which is the most tempting error, and the last relies on a "full mediation" label that the lesson advises against. (Section 1, 7.1 Statistical Mediation in Cross-Sectional Data and Table 8.2; Section 4, 7.4 Reporting a Path Model; Objectives 7.1 and 7.4)

12. A cross-sectional mediation analysis of social media use and depressive symptoms in adolescents, with sleep problems as the mediator, reports from medsens() that the ACME would equal zero at ρ = 0.40. Which interpretation is best?

ρ is not the proportion mediated. It is the residual correlation between the mediator and outcome models that an unmeasured confounder would have to produce to bring the indirect effect to zero.
medsens() addresses confounding of the mediator and the outcome, sleep problems and depressive symptoms, not of the exposure and the outcome. This option names the wrong pair of variables.
A larger ρ means a stronger confounder would be needed to remove the indirect association, but the sensitivity analysis does not rule such a confounder out or establish temporal order, so the result is not shown to be causal.
ρ is the residual correlation an unmeasured common cause of sleep problems and depressive symptoms would need to induce to remove the indirect association. A value of about 0.4 takes a fairly strong confounder, but a cross-sectional survey still lacks temporal order.
The correct interpretation reads ρ as the strength of mediator-outcome confounding needed to remove the indirect association. ρ is the correlation between the residuals of the mediator model (sleep problems) and the outcome model (depressive symptoms) that an unmeasured common cause of those two variables would have to produce, beyond the covariates in the models; the second option names the wrong pair of variables. A plausible confounder must affect both sleep problems and depressive symptoms, such as anxiety or a history of depression. Robustness is judged by the size of ρ: values of about 0.15 to 0.25 mark a fragile result, while about 0.4 needs a fairly strong confounder and marks a moderately robust one; because a strong common cause is plausible here, the result is reported as sensitive to that possibility, and the sensitivity analysis says nothing about temporal order. (Section 3, 5.1 Sensitivity Analysis for Unmeasured Mediator-Outcome Confounding and Figure 8.9; Objective 5.1)

13. A path model of 1,000 adults has caregiving hours as the exposure, stress as the mediator and two outcomes, sleep problems and back pain. A reduced model leaves out the direct path from caregiving to sleep problems, which is 0.08 (p = 0.014) in the full, saturated model. The reduced model has chi-square 6.00 on 1 df (p = 0.014), CFI 0.994, TLI 0.964, RMSEA 0.071 and SRMR 0.015. Using these values and the comparison below, which conclusion is best?

ModelDfAICBICChisq diffPr(>Chisq)
Full015,23015,299
Reduced115,23415,2986.000.014
In large samples the chi-square test is significant for almost any model that leaves something out, so it is not decisive alone. The reduced model's indices show acceptable fit, and the BIC is part of the evidence to explain.
The fit indices and the comparison answer different questions: whether a model approximates the data, and whether a left-out path is detectable. A model can fit acceptably while a small path is still present.
The reduced model fits acceptably, yet the difference test and the AIC show that the direct path is small but detectable, while the BIC penalizes extra paths more. The full model is reported with the size of the direct path and the choice explained.
Acceptable fit does not mean the left-out path is absent; the difference test detects it. Calling the result full mediation would hide a path the comparison finds, and the label depends mainly on sample size.
The correct conclusion is to report the full model while explaining the evidence. The reduced model's CFI (0.994) and TLI (0.964) are above 0.95 and its SRMR (0.015) is below 0.08; its RMSEA (0.071) is above 0.06 but below 0.08, so acceptable, and far from 0.10. The chi-square difference test (6.00 on 1 df, p = 0.014) shows that leaving out the direct path makes the fit significantly worse, and the AIC is lower for the full model (15,230 against 15,234). The BIC is 1 point lower for the reduced model because it penalizes each extra path more heavily, so a small but detectable path can lose on the BIC. These results do not contradict each other: the reduced model approximates the data well, and the direct path is small but present, so the larger model is usually reported, with the size of each path. The last option is tempting, but "full mediation" would hide a path that the comparison detects. (Section 4, 6.3.1 Reading the Fit Indices, Table 8.10, and 6.3.2 Comparing Nested Models; Objectives 6.3 and 7.4)

14. A path model of 2,500 students links weekly hours of paid work to grades through exam stress. The standardized coefficients are 0.25 for work → stress, −0.30 for stress → grades and −0.05 (95% CI −0.10 to 0.00) for the direct path work → grades, and the R-squared for grades is 0.11. The standardized solution in R lists the defined indirect path (ind := a*b) as −0.075. Which reading is correct?

The standardized indirect path, the product of its two standardized paths, is larger in size than the direct path. R-squared is the share of variance in grades the model explains, so most of the variation in grades lies outside it.
R-squared measures the share of variance explained, not model fit. A model can fit well while explaining a modest share of the variance in an outcome.
A standardized coefficient is a difference in standard deviations, not a percentage of variance explained. The share of variance explained is given by R-squared.
Standardized paths are in standard deviation units, not per hour, and in a single survey they describe associations. Standardizing does not make a coefficient causal.
The correct reading compares the standardized paths and reads R-squared as variance explained. In a standardized solution the defined indirect path is the product of its two standardized paths, which R prints as −0.075, so weekly work hours one standard deviation higher go with grades about 0.08 standard deviations lower through stress, compared with −0.05 for the direct path. The R-squared of 0.11 means the model explains 11% of the variance in grades. R-squared measures variance explained, not fit, so the second option is wrong, and a standardized coefficient is neither a percentage of explained variance (the third option) nor a causal effect per hour (the last option). (Section 4, 6.4 Results from the Chosen Model and Table 8.11; Objective 6.4)

15. In a path model, physical activity is a single self-reported item. When it is replaced by a latent activity factor measured by three items, the standardized path from activity to fitness rises from 0.30 to 0.38. What is the most likely reason?

A latent factor does not add people with missing activity scores. Its effect on the path comes from separating the items' shared variation from their measurement error.
Measurement error in a single observed score attenuates its associations. A latent factor separates the variation its items share from their error, so the path is estimated with less attenuation and is usually stronger.
The gain depends on the items: a latent factor is only as meaningful as its measurement model, and it needs several good items. Larger paths are not guaranteed whatever the item quality.
A latent variable deals with measurement error, not with temporal order or unmeasured confounding. Fitted to the same data, the model cannot show that activity comes before fitness.
The correct reason is reduced attenuation. Measurement error in a single observed score weakens (attenuates) its correlations with other variables. A latent factor measured by several items separates the variation the items share from their error, so the structural path is estimated without that attenuation and is usually stronger, as the CSCS path from loneliness to depressive symptoms rose from 0.38 to 0.47. The gain depends on good items, which is why the third option is wrong, and a latent variable does nothing about temporal order (the last option) or unmeasured confounding. (Section 4, 6.5 From Path Analysis to Structural Equation Modelling and Activity 8.4; Objective 6.5)

16. A health region surveyed 1,600 adults with type 2 diabetes once. It asks whether the number of diabetes education sessions attended is associated with lower HbA1c partly through better medication adherence (a score from 0 to 10), and whether the association between sessions and adherence differs for adults aged 65 and over. Every model adjusts for health literacy and income, which the analyst's DAG shows as causes of both attending sessions and HbA1c. Using the output below from lm(adherence ~ sessions * age_grp + literacy + income), with "under 65" as the reference group, which statement is correct?

TermEstimatep-value
sessions0.40< 0.001
sessions:age_grp65 and over−0.250.010
> c(under_65 = coef(m)[["sessions"]],
+   age_65_plus = coef(m)[["sessions"]] + coef(m)[["sessions:age_grp65 and over"]])
   under_65 age_65_plus
       0.40        0.15 
This swaps the roles: health literacy causes both attending sessions and HbA1c, so it is a confounder, and adherence lies on the proposed pathway, so it is the mediator. Adding age group as a covariate fits one slope and does not test whether it differs.
Adjusting for age group fits one common sessions slope for both groups, so it cannot show whether the slope differs. That question needs the sessions × age group interaction.
A collider is a common effect of the exposure and the outcome, and age group is not caused by sessions or adherence. Here it is a proposed effect modifier, analysed with an interaction.
Health literacy is a confounder adjusted for in every model, adherence is the proposed mediator, and the age question concerns the size of an association, so it is effect modification. The interaction is significant and the printed slopes show a weaker association at 65 and over.
The correct statement gives each role and reads the two slopes. Health literacy affects both attending sessions and HbA1c, so it is a confounder and is adjusted for. Adherence lies on the proposed pathway from sessions to HbA1c, so it is the mediator. The question about age is whether the size of the sessions-adherence association differs between groups, which is effect modification, analysed with the sessions × age group interaction. The sessions coefficient (0.40) is the slope among adults under 65, R prints the slope at 65 and over as 0.15, and the interaction (−0.25, p = 0.010) shows that the slopes differ, so the association is weaker in the older group. Adjusting for age group fits one common slope and does not test whether it differs (the first and second options), and age group is not a common effect of sessions and adherence, so it is not a collider (the third option). (Section 1, 1.1 and 1.2, Table 8.1; Section 2, 3.1 Moderation as a Research Question, Table 8.3 and its callout, and 3.2 Fitting and Interpreting an Interaction Model, Table 8.4; Objectives 1.1, 1.2, 3.1 and 3.2)

✦ Before submitting: pass every section knowledge check (100%).

🏆 Congratulations!

This was the last lesson of HSCI 410. The methods of the course, from data cleaning and description through regression, generalized linear models, measurement and now mediation, moderation and path analysis, together form a complete workflow for analyzing a survey such as the CSCS. The course home lists every lesson, so that earlier material can be revisited.

You have successfully completed this lesson: Mediation, Moderation and Path Analysis.

Your responses have been downloaded automatically.

Return to the HSCI 410 course home →

HSCI 410 Course Home →