Show how the data are loaded
library(tidyverse)
wave2 <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/smartmix_wave2.csv")Driving question: Why — and for whom — does it work?
An experiment answers the question whether something works, on average. Managers rarely stop there. If Smart Mix increases listening time by 3 hours on average, the next questions are: does it work for everyone, or mainly for some users — and why does it work? The first question is about heterogeneity of the effect, answered with moderation analysis (interaction terms). The second is about the mechanism, answered with mediation analysis. Both reuse the regression toolkit of Chapter 5, with one new ingredient: the product of two variables. After working through this chapter you will be able to:
Session 7 covers Section 6.1 to Section 6.5, Section 6.7, and Section 6.8, which ends with a coding block of two cases; Section 6.6 is reading.
After the first A/B test (Chapter 4), the product team ran a second, larger Smart Mix experiment: 1200 users, randomly assigned, and this time with information about each user — their plan (free or Premium), their listening before the experiment, their tenure and device — and one more variable: the number of new artists each user discovered during the four weeks. The team had a hypothesis about why Smart Mix works: it exposes users to music they would not have found themselves.
library(tidyverse)
wave2 <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/smartmix_wave2.csv")| Variable | Description |
|---|---|
smart_mix |
1 if the user was assigned to Smart Mix (randomized), 0 for control |
hours |
Listening hours in the four weeks of the experiment |
premium |
1 for Premium subscribers, 0 for free users |
prior_hours |
Listening hours in the month before the experiment |
tenure, device |
Months since sign-up; main device |
new_artists |
Number of new artists the user listened to during the experiment (the proposed mediator) |
The average effect is clear: Smart Mix users listened 3.7 hours more (95% CI 3.1 to 4.3), estimated with the covariates as controls — which, in a randomized experiment, is not needed for unbiasedness but tightens the confidence interval. Now the product team’s two questions:
The first question is answered by moderation: the effect of Smart Mix depends on another variable (the moderator). The second by mediation: the effect of Smart Mix runs through another variable (the mediator). The distinction matters, because the two are easy to confuse: a moderator changes how large the effect is; a mediator is part of the path from cause to outcome.
In every regression so far, the effect of a variable was the same for everybody: one coefficient, one slope. An interaction term lets the effect of one variable depend on another. The model
\[ y = \beta_0 + \beta_1 x + \beta_2 z + \beta_3 \, (x \times z) + \varepsilon \]
contains the product of \(x\) and \(z\) as a third predictor. The marginal effect of \(x\) — how much \(y\) changes when \(x\) increases by one unit — is no longer \(\beta_1\) alone:
\[ \frac{\partial y}{\partial x} = \beta_1 + \beta_3 z \]
The effect of \(x\) now depends on \(z\): \(\beta_1\) is the effect of \(x\) when \(z\) is zero, and \(\beta_3\) says by how much the effect changes for each unit of \(z\). Symmetrically, the effect of \(z\) is \(\beta_2 + \beta_3 x\). Two rules follow:
Figure 6.1 shows what an interaction looks like when \(z\) is a group indicator: without interaction, the lines for the two groups are parallel (same slope, different level); with an interaction, the slopes differ; and in a crossover, the effect of \(x\) changes sign between groups. The interaction coefficient \(\beta_3\) is simply the difference between the two slopes.
In a formula, x * z is shorthand for x + z + x:z — both variables and their product. Writing x:z alone (without the main terms) is the mistake described above; x * z always does the right thing. (As in Chapter 5, the coefficient tables in this chapter are printed with round(coef(summary(model)), 3) — estimate, standard error, t value and p-value, with p-values below 0.0005 shown as 0.000 — or with summary(model) when the full output is of interest.)
This is the most common interaction in practice, and it has two faces: a treatment effect that differs between groups, and a slope that differs between groups. They are the same model.
Does Smart Mix help free users more than Premium users? For the product team this is more than a statistical detail: if the effect is concentrated among free users, Smart Mix belongs in the free tier’s roadmap and in the upgrade pitch, not in the Premium feature list. The raw means (Figure 6.2) suggest so: among free users, the Smart Mix group listens about 4.6 hours more than the control group; among Premium users, about 1 hour more.
The regression with the interaction smart_mix * premium quantifies this and adds the uncertainty:
model_plan <- lm(hours ~ smart_mix * premium + prior_hours + tenure, data = wave2)
summary(model_plan)
Call:
lm(formula = hours ~ smart_mix * premium + prior_hours + tenure,
data = wave2)
Residuals:
Min 1Q Median 3Q Max
-17.889 -3.336 0.164 3.422 15.940
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.55997 0.46882 3.33 0.0009 ***
smart_mix 4.99874 0.37835 13.21 < 2e-16 ***
premium 2.68460 0.43130 6.22 6.7e-10 ***
prior_hours 0.75163 0.01709 43.97 < 2e-16 ***
tenure 0.02791 0.00857 3.26 0.0012 **
smart_mix:premium -3.11146 0.59005 -5.27 1.6e-07 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 5.02 on 1194 degrees of freedom
Multiple R-squared: 0.65, Adjusted R-squared: 0.649
F-statistic: 444 on 5 and 1194 DF, p-value: <2e-16
Reading the coefficients with the marginal-effect rule:
smart_mix (5): the effect of Smart Mix for free users (premium = 0).smart_mix:premium (-3.11): how much the effect differs for Premium users. Its p-value tests whether the two effects differ — this is the test of heterogeneity.premium (2.68): the difference between Premium and free users in the control group (smart_mix = 0) — not an overall Premium effect.The coefficients (5.0 and 1.9) are not exactly the gaps in Figure 6.2 (4.6 and 1.0): the chart shows raw means, while the regression holds prior listening and tenure constant. The Smart Mix users of both plans happen to have slightly lower prior listening than their control groups, and the model corrects for this chance imbalance. Because Smart Mix was randomized, both comparisons are unbiased — the adjusted one is simply more precise (Section 6.1).
Written as a formula, the marginal effect of Smart Mix is
\[ \text{Effect of Smart Mix} = \beta_{\text{smart\_mix}} + \beta_{\text{smart\_mix:premium}} \times \text{premium}, \]
which R computes from the coefficient vector:
b <- coef(model_plan)
b["smart_mix"] + b["smart_mix:premium"] * c(free = 0, premium = 1) free premium
4.999 1.887
The confidence interval of the Premium effect is not in the regression output: it combines two coefficients, so its standard error depends on both their standard errors and their covariance. The emtrends() function of the emmeans package does this computation for you — it reports the “trend” (here: the effect) of smart_mix at each value of the moderator, with its standard error and confidence interval:
library(emmeans)
emtrends(model_plan, ~ premium, var = "smart_mix") premium smart_mix.trend SE df lower.CL upper.CL
0 5.00 0.378 1194 4.256 5.74
1 1.89 0.453 1194 0.998 2.78
Results are averaged over the levels of: smart_mix
Confidence level used: 0.95
Figure 6.3 shows the same two effects as a picture. Smart Mix helps free users a lot (5.0 hours, 95% CI 4.3 to 5.7) and Premium users a little (1.9 hours, CI 1.0 to 2.8) — a finding the product team can act on: the feature is worth promoting to free users first. Note the division of labor: the interaction coefficient tests whether the two effects differ; the two marginal effects say what they are. Report both.
The same model structure answers a different-looking question. In the promotion campaigns of Chapter 5 (a second year of campaigns, promo), does the elasticity of streams with respect to spend differ between genres? For the label, this is a budget-allocation question: if the elasticity differs, the next promotion euro should go to the genre where a percent of budget buys the most streams. Here the continuous variable is log(spend) and the groups are genres:
promo <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/promo_campaigns.csv") |>
mutate(genre = factor(genre, levels = c("Pop", "HipHop/Rap", "Rock", "Electro/Dance")))model_genre <- lm(log(streams) ~ log(spend) * genre + log(followers) + placements, data = promo)
round(coef(summary(model_genre)), 3) Estimate Std. Error t value Pr(>|t|)
(Intercept) -3.648 0.321 -11.357 0.000
log(spend) 0.206 0.033 6.171 0.000
genreHipHop/Rap -2.058 0.430 -4.786 0.000
genreRock 0.356 0.654 0.544 0.587
genreElectro/Dance 0.021 0.616 0.034 0.973
log(followers) 0.507 0.015 33.456 0.000
placements 0.122 0.011 11.417 0.000
log(spend):genreHipHop/Rap 0.268 0.052 5.178 0.000
log(spend):genreRock -0.053 0.079 -0.669 0.504
log(spend):genreElectro/Dance 0.005 0.076 0.068 0.946
log(spend) (0.21) is the spend elasticity for Pop, the reference genre; log(spend):genreHipHop/Rap (0.27) says that the elasticity for HipHop/Rap is higher by that amount — 0.47 in total (Figure 6.5). For Rock and Electro/Dance, the interaction terms are small and not significant: no evidence that their elasticities differ from Pop’s. The genre main effects (genreHipHop/Rap etc.) are the level differences at log(spend) = 0, i.e., at a spend of 1 euro, because log(1) = 0 — a reminder that main effects in an interaction model refer to the zero of the other variable, which here is a spend level that no campaign comes close to.
The elasticity of each genre follows the same marginal-effect rule, \(\text{Elasticity}_{\text{genre}} = \beta_{\log(\text{spend})} + \beta_{\log(\text{spend}):\text{genre}}\) (with 0 for the reference genre), and emtrends() adds the confidence intervals:
b <- coef(model_genre)
elasticity <- b["log(spend)"] +
c(0, b["log(spend):genreHipHop/Rap"], b["log(spend):genreRock"], b["log(spend):genreElectro/Dance"])
names(elasticity) <- levels(promo$genre)
elasticity Pop HipHop/Rap Rock Electro/Dance
0.2058 0.4737 0.1532 0.2109
emtrends(model_genre, ~ genre, var = "log(spend)") genre log(spend).trend SE df lower.CL upper.CL
Pop 0.206 0.0334 590 0.1403 0.271
HipHop/Rap 0.474 0.0396 590 0.3959 0.551
Rock 0.153 0.0712 590 0.0133 0.293
Electro/Dance 0.211 0.0679 590 0.0776 0.344
Confidence level used: 0.95
A 1% increase in spend goes with about 0.21% more streams for Pop campaigns and 0.47% more for HipHop/Rap campaigns; the intervals of Rock and Electro/Dance overlap Pop’s. Figure 6.4 shows the four elasticities with their confidence intervals — the chart to put in front of the label’s management (plot() on the emtrends() object produces a similar one).
Does Smart Mix help light listeners more than heavy listeners? If so, the feature’s onboarding should target light listeners, and heavy listeners need a different lever — a targeting question that only a continuous moderator can answer.
Does the effect of Smart Mix depend on how much a user listened before? Now the moderator is continuous, and the interaction smart_mix * prior_hours lets the Smart Mix effect change by a constant amount per hour of prior listening:
model_prior <- lm(hours ~ smart_mix * prior_hours + premium + tenure, data = wave2)
round(coef(summary(model_prior)), 3) Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.446 0.532 2.720 0.007
smart_mix 5.391 0.660 8.164 0.000
prior_hours 0.797 0.023 34.426 0.000
premium 1.041 0.301 3.462 0.001
tenure 0.027 0.009 3.152 0.002
smart_mix:prior_hours -0.096 0.034 -2.822 0.005
The marginal effect of Smart Mix is now a function of prior listening,
\[ \text{Effect of Smart Mix} = \beta_{\text{smart\_mix}} + \beta_{\text{smart\_mix:prior\_hours}} \times \text{prior\_hours} = 5.39 - 0.096 \times \text{prior\_hours}, \]
i.e., about 4.4 hours for a user who listened 10 hours before, and 2.5 hours for one who listened 30 (Figure 6.6). In R, from the coefficients and with confidence intervals:
b <- coef(model_prior)
b["smart_mix"] + b["smart_mix:prior_hours"] * c(10, 20, 30)[1] 4.427 3.463 2.499
emtrends(model_prior, ~ prior_hours, var = "smart_mix", at = list(prior_hours = c(10, 20, 30))) prior_hours smart_mix.trend SE df lower.CL upper.CL
10 4.43 0.385 1194 3.67 5.18
20 3.46 0.307 1194 2.86 4.07
30 2.50 0.523 1194 1.47 3.52
Results are averaged over the levels of: smart_mix, premium
Confidence level used: 0.95
The interaction is significant: Smart Mix helps light listeners more. Note again that smart_mix alone (5.39) is the effect for a user with zero prior listening — a user who hardly exists in the data. With a continuous moderator, always report the effect at a few meaningful values — e.g., the 10th, 50th, and 90th percentiles of the moderator, here 9, 15, and 28 hours — or as a curve with its confidence band.
A marginal effect such as \(\beta_1 + \beta_3 z\) is a combination of two estimated coefficients, so its standard error depends on both their standard errors and their covariance: \(\text{SE} = \sqrt{V_{11} + z^2 V_{33} + 2 z V_{13}}\), where \(V\) is the covariance matrix of the coefficients, vcov(model). This is what Figure 6.6 and Figure 6.3 compute. In practice, packages do it for you: emmeans::emtrends() for slopes by group, emmeans::emmeans() for group means, and the interactions package for plots of marginal effects.
Fit the interaction of Smart Mix with device: model_device <- lm(hours ~ smart_mix * device + prior_hours + premium + tenure, data = wave2). For which device is the effect of Smart Mix largest? Compute the effect for each device from the coefficients (or with emtrends(model_device, ~ device, var = "smart_mix")), and check whether the differences are significant.
When both interacting variables are continuous, the model is the same, but the interpretation needs more care. In the campaign data, is the spend elasticity larger for artists with a bigger follower base — do promotion and reach reinforce each other? For the label this decides whether to concentrate promotion budgets on artists who already have an audience, or to deliberately counter the “rich get richer” dynamic. The model is
\[ \log(\text{streams}) = \beta_0 + \beta_1 \log(\text{spend}) + \beta_2 \log(\text{followers}) + \beta_3 \log(\text{spend}) \times \log(\text{followers}) + \dots, \]
and the marginal-effect rule gives the spend elasticity as \(\beta_1 + \beta_3 \log(\text{followers})\): it is no longer one number but a function of the follower base, and \(\beta_3\) says by how much it changes per unit of \(\log(\text{followers})\).
model_cc <- lm(log(streams) ~ log(spend) * log(followers) + placements + genre, data = promo)
round(coef(summary(model_cc)), 3) Estimate Std. Error t value Pr(>|t|)
(Intercept) 5.410 1.506 3.593 0.000
log(spend) -0.896 0.183 -4.901 0.000
log(followers) -0.422 0.143 -2.960 0.003
placements 0.121 0.011 11.435 0.000
genreHipHop/Rap 0.165 0.044 3.767 0.000
genreRock -0.096 0.059 -1.624 0.105
genreElectro/Dance 0.065 0.058 1.129 0.260
log(spend):log(followers) 0.113 0.017 6.528 0.000
The interaction (0.113) is clearly positive: each additional unit of log(followers) — a follower base multiplied by e ≈ 2.7, since log(2.7 × followers) = log(followers) + 1 — adds 0.11 to the spend elasticity, so the same percentage budget increase buys a larger percentage gain for a bigger artist. Promotion and reach reinforce each other. But the “main effects” look absurd — log(spend) is -0.9, a negative elasticity. The marginal-effect rule explains why: log(spend) is the elasticity for an artist with log(followers) = 0, i.e., with one follower (log(1) = 0). Nobody in the data is anywhere near that — the median artist has 36,400 followers.
The fix is to center the interacting variables at their means before forming the product. The interaction coefficient does not change; the main effects become the marginal effects at the mean of the other variable:
promo_c <- promo |>
mutate(log_spend_c = log(spend) - mean(log(spend)),
log_fol_c = log(followers) - mean(log(followers)))
model_cc_centered <- lm(log(streams) ~ log_spend_c * log_fol_c + placements + genre, data = promo_c)
round(coef(summary(model_cc_centered)), 3) Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.411 0.044 77.500 0.000
log_spend_c 0.299 0.022 13.314 0.000
log_fol_c 0.508 0.015 33.870 0.000
placements 0.121 0.011 11.435 0.000
genreHipHop/Rap 0.165 0.044 3.767 0.000
genreRock -0.096 0.059 -1.624 0.105
genreElectro/Dance 0.065 0.058 1.129 0.260
log_spend_c:log_fol_c 0.113 0.017 6.528 0.000
Now log_spend_c (0.3) is the spend elasticity for an artist with an average (log) follower count (about 39,000 followers), and the interaction says that it rises by 0.113 for each unit of log followers — that is, each time the follower base grows by a factor of about 2.7. The interaction coefficient, the other coefficients, R² and all predictions are identical in the two versions: centering changes what the main effects mean, not the model.
The marginal-effect rule gives the elasticity for any follower base,
\[ \text{Elasticity} = \beta_{\text{log\_spend\_c}} + \beta_{\text{log\_spend\_c:log\_fol\_c}} \times \big(\log(\text{followers}) - \overline{\log(\text{followers})}\big), \]
for instance at the 10th, 50th, and 90th percentile of the follower distribution (about 7,800, 36,000, and 205,000 followers):
b <- coef(model_cc_centered)
fol_q <- quantile(promo$followers, c(0.1, 0.5, 0.9))
b["log_spend_c"] + b["log_spend_c:log_fol_c"] * (log(fol_q) - mean(log(promo$followers))) 10% 50% 90%
0.1175 0.2917 0.4869
emtrends(model_cc, ~ followers, var = "log(spend)", at = list(followers = unname(fol_q))) followers log(spend).trend SE df lower.CL upper.CL
7806 0.117 0.0345 592 0.0498 0.185
36420 0.292 0.0224 592 0.2477 0.336
204650 0.487 0.0378 592 0.4128 0.561
Results are averaged over the levels of: genre
Confidence level used: 0.95
(emtrends() works on the uncentered model as well, because the two models are the same model.) Figure 6.7 plots the marginal effect across the whole follower distribution: for an artist at the 10th percentile, a 10% increase in spend brings about 1.2% more streams; at the 90th percentile, about 4.9%.
Two practical notes. First, centering is cosmetic for the interaction and the model’s fit (predictions are identical), but essential for reading the main effects. Second, with two continuous variables, a plot of the marginal effect — or predicted values at a few combinations — communicates far better than the coefficient table.
Centering subtracts the mean; standardizing additionally divides by the standard deviation. Either changes the main effects (now interpreted at the mean) and the intercept, but not the interaction coefficient (for centering) or the model fit. An old recommendation was that centering reduces multicollinearity between \(x\), \(z\), and \(x \times z\). It does lower the correlation between the terms, but it does not change the standard error of the interaction or any marginal effect — the gain is interpretability, not precision.
Interactions between two categorical variables are the natural analysis of factorial experiments, in which two treatments are manipulated at once. The streaming service’s marketing team wanted to know whether ads designed with AI are judged as creative as ads designed by humans — and whether it matters if people know who made them. Behind the question is a policy decision: whether to disclose AI involvement in the service’s advertising, and the interaction tells the team when disclosure costs creativity points and when it does not. 360 respondents each saw one ad for the service and rated its creativity (0–100). The design has two factors: the source of the design (made by a human, by AI, or by a human with AI) and the disclosure of the source (revealed to the respondent or not). Each of the 2 × 3 = 6 combinations — the cells — had 60 respondents, assigned at random.
ads <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/ad_designs.csv") |>
mutate(source = factor(source, levels = c("Human", "AI", "Human + AI")),
disclosure = factor(disclosure, levels = c("Revealed", "Not revealed")))The cell means tell the story (Figure 6.8): when the source is revealed, human designs are rated clearly more creative than AI or hybrid designs. When it is not revealed, the AI and hybrid designs are rated as creative as the human ones — in fact slightly higher. The effect of the source depends on disclosure: a textbook interaction, with crossing lines.
ads |>
group_by(source, disclosure) |>
summarise(n = n(), mean_creativity = mean(creativity), .groups = "drop")# A tibble: 6 × 4
source disclosure n mean_creativity
<fct> <fct> <int> <dbl>
1 Human Revealed 60 61.8
2 Human Not revealed 60 52.1
3 AI Revealed 60 48.3
4 AI Not revealed 60 60.8
5 Human + AI Revealed 60 43.6
6 Human + AI Not revealed 60 62.0
The regression with source * disclosure reproduces the six cell means with six coefficients. With the reference categories Human and Revealed, each coefficient has a precise meaning (Table 6.2):
model_ads <- lm(creativity ~ source * disclosure, data = ads)
round(coef(summary(model_ads)), 3) Estimate Std. Error t value Pr(>|t|)
(Intercept) 61.800 1.854 33.330 0
sourceAI -13.533 2.622 -5.161 0
sourceHuman + AI -18.250 2.622 -6.960 0
disclosureNot revealed -9.667 2.622 -3.686 0
sourceAI:disclosureNot revealed 22.233 3.708 5.996 0
sourceHuman + AI:disclosureNot revealed 28.150 3.708 7.591 0
| Coefficient | Value | Meaning |
|---|---|---|
(Intercept) |
61.8 | Mean rating of human designs when the source is revealed (the reference cell) |
sourceAI |
-13.5 | AI designs, when revealed, are rated this much lower than human designs |
sourceHuman + AI |
-18.2 | Hybrid designs, when revealed, are rated this much lower than human designs |
disclosureNot revealed |
-9.7 | Human designs are rated this much lower when the source is not revealed |
sourceAI:disclosureNot revealed |
22.2 | AI designs gain this much extra when the source is not revealed, beyond what the two main effects would predict |
sourceHuman + AI:disclosureNot revealed |
28.1 | The same for hybrid designs |
Any cell mean can be rebuilt from these: the mean for AI designs with the source not revealed is 61.8 + (-13.5) + (-9.7) + 22.2 = 60.8. The interaction coefficients are large and significant: disclosure changes the ranking of the designs.
With several categories per factor, the question “is there an interaction?” involves several coefficients at once (here two). The ANOVA table tests each factor and the interaction as a whole, the same logic as the ANOVA in Chapter 4:
anova(model_ads)Analysis of Variance Table
Response: creativity
Df Sum Sq Mean Sq F value Pr(>F)
source 2 1055 527 2.56 0.079 .
disclosure 1 4572 4572 22.17 3.6e-06 ***
source:disclosure 2 13218 6609 32.04 1.6e-13 ***
Residuals 354 73021 206
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The interaction source:disclosure is highly significant: the effect of the source depends on disclosure. When the interaction is significant, the main effects should not be interpreted on their own — “AI designs are rated lower on average” is true only when averaged over a condition in which they are rated higher and one in which they are rated lower.
The interaction tells us that the effect of the source depends on disclosure; it does not tell us which cells differ. For that, we compare the cell means pairwise, with the usual correction for multiple comparisons (Chapter 4). The emmeans package computes the estimated marginal means — the model’s predicted cell means with their standard errors — and the pairwise contrasts:
library(emmeans)
emm <- emmeans(model_ads, ~ source | disclosure)
emmdisclosure = Revealed:
source emmean SE df lower.CL upper.CL
Human 61.8 1.85 354 58.1 65.5
AI 48.3 1.85 354 44.6 51.9
Human + AI 43.5 1.85 354 39.9 47.2
disclosure = Not revealed:
source emmean SE df lower.CL upper.CL
Human 52.1 1.85 354 48.5 55.8
AI 60.8 1.85 354 57.2 64.5
Human + AI 62.0 1.85 354 58.4 65.7
Confidence level used: 0.95
pairs(emm, adjust = "bonferroni")disclosure = Revealed:
contrast estimate SE df t.ratio p.value
Human - AI 13.53 2.62 354 5.161 <.0001
Human - (Human + AI) 18.25 2.62 354 6.960 <.0001
AI - (Human + AI) 4.72 2.62 354 1.799 0.2187
disclosure = Not revealed:
contrast estimate SE df t.ratio p.value
Human - AI -8.70 2.62 354 -3.318 0.0030
Human - (Human + AI) -9.90 2.62 354 -3.775 0.0006
AI - (Human + AI) -1.20 2.62 354 -0.458 1.0000
P value adjustment: bonferroni method for 3 tests
The output answers the question at the level a manager needs: when the source is revealed, human designs beat both AI (by about 14 points) and hybrid designs, which do not differ from each other; when the source is not revealed, the ranking flips, and the AI and hybrid designs beat the human one by about 9–10 points. The p-values are Bonferroni-adjusted for the three comparisons within each disclosure condition — the correction of Chapter 4. (pairs(emm) without the argument uses Tukey’s HSD, which is designed for exactly this situation, all pairwise comparisons, and is slightly less conservative; the picture is the same.)
This two-step logic — an overall test of the interaction, then corrected comparisons of the cells — is the same as for the one-way ANOVA, with one extra dimension.
anova() on an lm object produces sequential (Type I) sums of squares: each term is tested after the terms listed before it. With equal cell sizes — a balanced design, as here — the order does not matter and all common ANOVA tables agree. With unbalanced cells (different numbers of respondents, typical for survey experiments with dropouts), the sequential table depends on the order of the factors; car::Anova(model_ads, type = 2) gives the usual order-independent tests. The regression coefficients and the emmeans results are not affected by this issue.
Rebuild the cell mean for hybrid designs with the source not revealed from the coefficients of model_ads, and check it against the table of cell means. Then: which single number in the regression output answers the question “does disclosure change the rating of hybrid designs more than it changes the rating of human designs”?
Heterogeneity is where analytics gets interesting — and where it goes wrong most easily.
Subgroup fishing. Any data set with a few covariates offers dozens of possible subgroups: by plan, device, tenure, age, country, prior listening, and all their combinations. Testing the effect in every subgroup is multiple testing (Chapter 4): with 20 subgroups and no true heterogeneity at all, the chance of finding at least one “significant” subgroup effect is \(1 - 0.95^{20}\) = 64% (Figure 6.9). A subgroup effect found this way is far more likely to be noise than a discovery — and it will not replicate.
Interactions need large samples. A difference between two effects is estimated far less precisely than an effect itself: for two groups of equal size, the standard error of the difference between their effects is twice the standard error of the overall effect, so detecting an interaction of the same size as a main effect needs about four times as many participants (Figure 6.10). Underpowered interaction tests do double damage: they miss real heterogeneity, and the heterogeneity they do find tends to be exaggerated.
What to do instead. Decide before the experiment which moderators you expect, and why — and pre-register them (Chapter 4). Test those with the interaction model of this chapter. Everything else is exploratory: report it as a hypothesis for the next experiment, not as a finding of this one. And when the interaction is not significant, say “we found no evidence that the effect differs”, not “the effect is the same for everyone” — an underpowered test cannot show that.
In a two-group experiment with \(n\) users per group, the standard error of the treatment effect is about \(\sigma \sqrt{2/n}\). Splitting the sample into two equal subgroups and comparing their effects gives a standard error of \(\sigma \sqrt{2/(n/2)} \cdot \sqrt{2} = 2 \sigma \sqrt{2/n}\) — twice as large. Because the required sample size grows with the square of the standard error, the interaction needs four times the sample for the same power, if it is as large as the main effect. Interactions are typically smaller than main effects, which makes the ratio worse. power.t.test() with the appropriate standard deviation, or a simulation, gives the exact numbers for a planned design.
Back to the product team’s second question. Smart Mix increases listening time — but how? The hypothesis: Smart Mix makes users discover new artists, and discovering new artists makes them listen more. If this is right, part of the effect of Smart Mix runs through discovery, and the rest does not (Figure 6.11):
Mediation analysis estimates the three paths with regressions. First, does Smart Mix affect the mediator (path a)?
model_m <- lm(new_artists ~ smart_mix + prior_hours + premium, data = wave2)
round(coef(summary(model_m)), 3)["smart_mix", ] Estimate Std. Error t value Pr(>|t|)
3.619 0.141 25.648 0.000
Yes: Smart Mix users discovered 3.6 more new artists. Second, does the mediator affect the outcome, holding Smart Mix constant (path b), and what is left of the Smart Mix effect once the mediator is in the model (the direct effect c′)?
model_y <- lm(hours ~ smart_mix + new_artists + prior_hours + premium + tenure, data = wave2)
round(coef(summary(model_y)), 3)[c("smart_mix", "new_artists"), ] Estimate Std. Error t value Pr(>|t|)
smart_mix 2.306 0.360 6.414 0
new_artists 0.391 0.059 6.606 0
Each new artist goes with 0.39 additional listening hours (b), and the direct effect of Smart Mix, with discovery held constant, is 2.31 hours (c′) — down from the total effect of 3.72. The indirect effect is the product of the two path coefficients:
a <- coef(model_m)["smart_mix"]
b <- coef(model_y)["new_artists"]
indirect <- a * b
c(indirect = unname(indirect), direct = unname(coef(model_y)["smart_mix"]), total = unname(indirect + coef(model_y)["smart_mix"]))indirect direct total
1.415 2.306 3.721
About 1.41 of the 3.72 hours — 38% of the effect — run through the discovery of new artists; the rest is direct. For the product team, this means: discovery is an important mechanism, but not the only one, and improving the discovery feature can be expected to improve roughly a third of the effect. Figure 6.12 shows the three estimated paths in the diagram.
The indirect effect is a product of two estimates, and its sampling distribution is not normal, so the usual formula for a standard error does not apply. The standard solution is the bootstrap (Chapter 3): resample the users with replacement, re-estimate both regressions, and look at the distribution of the product:
set.seed(1)
boot_indirect <- replicate(2000, {
idx <- sample(nrow(wave2), replace = TRUE)
d_boot <- wave2[idx, ]
coef(lm(new_artists ~ smart_mix + prior_hours + premium, data = d_boot))["smart_mix"] *
coef(lm(hours ~ smart_mix + new_artists + prior_hours + premium + tenure, data = d_boot))["new_artists"]
})
quantile(boot_indirect, c(0.025, 0.975)) 2.5% 97.5%
0.9861 1.8632
The 95% bootstrap interval of the indirect effect excludes zero: the mediation is statistically reliable. Reporting a mediation analysis means reporting all three numbers with their uncertainty: the total effect, the direct effect, and the indirect effect with its bootstrap interval — plus the share of the effect that is mediated.
mediation packageThe mediation package (Imai et al. 2010) automates exactly this procedure. Given the two regressions, mediate() re-estimates them on bootstrap samples and reports the average causal mediation effect (ACME — the indirect effect), the average direct effect (ADE), the total effect, and the proportion mediated, each with a bootstrap confidence interval:
library(mediation) # install.packages("mediation")
set.seed(1)
med <- mediate(model_m, model_y, treat = "smart_mix", mediator = "new_artists", boot = TRUE, sims = 1000)
summary(med)Causal Mediation Analysis
Nonparametric Bootstrap Confidence Intervals with the Percentile Method
Estimate 95% CI Lower 95% CI Upper p-value
ACME 1.415 0.981 1.848 <2e-16 ***
ADE 2.306 1.628 3.001 <2e-16 ***
Total Effect 3.721 3.151 4.298 <2e-16 ***
Prop. Mediated 0.380 0.261 0.516 <2e-16 ***
Sample Size Used: 1200
Simulations: 1000
The numbers are the same as above, up to bootstrap noise: the package does nothing that the three regressions and the bootstrap loop do not do — but it does it in one line, and it also handles non-linear outcome models, such as a logistic regression for a yes/no outcome. Both routes are fine for your group project; the manual version has the advantage that you see what is being computed.
With several candidate mediators (discovery, playlist use, notifications), each can be examined in turn, but their indirect effects are only separable if the mediators do not affect each other — an assumption that needs an argument. The formal assumption behind the decomposition is sequential ignorability: (1) the treatment is as good as randomly assigned given the covariates, and (2) the mediator is as good as randomly assigned given the treatment and the covariates. In a randomized experiment, (1) holds by design; (2) is the untestable part discussed below. Sensitivity analyses (e.g., medsens() in the mediation package) show how strong an unobserved confounder of mediator and outcome would have to be to explain the mediation away.
The widget shows the catch. Randomizing Smart Mix identifies the total effect: users were assigned by coin flip, so the groups are comparable. But nobody randomized the mediator. Users who discovered many new artists chose to do so — perhaps because they are curious, or had time on their hands — and such users may listen more for the same reasons. The path b then mixes the effect of discovery with the effect of curiosity, exactly the confounding problem of Chapter 5, one step down the causal chain. The decomposition into direct and indirect effects is only valid if there are no unobserved confounders of the mediator–outcome relationship (given the treatment and the covariates). This assumption is as untestable as its cousin in Chapter 5, and it is the reason why mediation results deserve more caution than the total effect they decompose. What helps: measuring and adjusting for likely confounders of the mediator (prior listening and plan are in the models above for this reason), and — best of all — experiments that manipulate the mediator directly, e.g., a version of Smart Mix with and without the discovery feature.
Your experiment randomizes one factor with two or three conditions and measures one or more outcomes with about 120 respondents. It must also include at least one moderator and at least one mediator — this chapter is the toolkit for both, and the next session (survey design) is where you build them into the questionnaire.
Your moderator. Choose a moderator that is central to your topic and for which you can state in advance which direction you expect — e.g., “the effect of the sustainability label should be larger for respondents who care about the environment”. Measure it before the manipulation (so that it cannot be affected by it), and test it with outcome ~ condition * moderator; report the effect of the condition at meaningful values of the moderator (Section 6.3). Keep expectations modest: with 60 respondents per condition, you can detect only large interactions, so “we found no evidence that the effect differs” is a legitimate — and often the honest — result. A 2 × 2 design (two manipulated factors) is the cleaner way to study a moderator you can manipulate, but it spreads your respondents over four cells of 30 — enough for a demonstration, rarely for a precise estimate.
Your mediator. Choose the mechanism you believe in — perceived quality, trust, authenticity, attention — and measure it after the manipulation and before the outcome. The three regressions and the bootstrap of Section 6.7 (or mediate()) give you the total, direct, and indirect effect and the share mediated. State the assumption the decomposition rests on, and measure plausible confounders of the mediator–outcome relationship before the manipulation so that you can adjust for them. A mediator also protects you against the empty result “the manipulation had no effect”: a manipulation check and a mediator tell you where the chain broke.
Reporting. Moderation: “The effect of the label was 0.9 scale points for environmentally concerned respondents and 0.2 for the others; the interaction was significant (p = .03) / not significant (p = .40), so we found no evidence that the effect differs.” Mediation: “Of the total effect of 0.6 points, 0.25 (bootstrap 95% CI [0.05; 0.48]) ran through perceived quality.” And in both cases: which analyses were planned, and which were exploratory.
Case 1: the climate-neutral shipping label. An online shop randomly showed 1,000 customers of its customer panel a “climate-neutral shipping” label at checkout (label = 1) or not (label = 0). The data set green_label.csv records the order value in euros (order_value), the customer segment (segment: new or returning), and the importance the customer attaches to sustainability, from an earlier panel survey (eco_score, 1–7).
order_value ~ label * segment. Compute the label effect for each segment from the coefficients and with emtrends(). Do the effects differ? How would you report this?order_value ~ label * eco_score. Compute the label effect for a score of 2, 4, and 6. What does the coefficient of label alone mean here — and why should you not report it?Case 2: the story behind the coffee. A survey experiment of the kind you run in your group project: 320 respondents saw either a factual product description of a specialty coffee (“Facts”) or one that tells the story of the farm (“Story”), assigned at random. Afterwards they rated the perceived authenticity of the brand (mean of three 1–7 items; the mediator) and stated their willingness to pay for a 250 g pack (wtp, euros). Their coffee involvement (1–7) was measured before the manipulation. The data are in coffee_story.csv.
involvement as a control variable in both regressions. Compute the indirect effect and the share mediated.mediate()).The solutions will be available after the session.
The course started with four kinds of questions. By now, you have tools for all of them: description (Chapter 2), prediction (Chapter 5), causal effects from experiments (Chapter 4) and — with assumptions — from observational data (Chapter 5), and in this chapter, the two questions that come after the effect: for whom, and why. The prescriptive question — what should we do? — is where all of them meet: an action that works on average, for the right customers, for understood reasons, and whose effect size justifies its cost.
The toolkit is a regression with a product term, used in two ways. Moderation asks whether the effect differs across values of a third variable; mediation asks whether the effect passes through it. Both are more demanding than the average effect — statistically (interactions need large samples; indirect effects need the bootstrap) and conceptually (mediation needs an assumption that randomization does not provide). Used with these limits in mind, they turn a yes/no result into something a product team can build on.
(LC6.1) In the model hours ~ smart_mix * premium + prior_hours, the coefficient of smart_mix is 5.0 and the coefficient of smart_mix:premium is −3.1. What is the effect of Smart Mix for free users? For Premium users? What does the p-value of the interaction test?
(LC6.2) Which statements about interaction models are correct?
(LC6.3) A marketing team finds that a discount increases purchases by 12% among new customers and by 2% among existing customers. The interaction has p = 0.08 with 150 customers per group. How should the result be reported?
(LC6.4) In a 2 × 2 experiment (price framing: monthly vs. yearly; trial: yes vs. no), the regression gives: intercept 40, framingYearly −5, trialYes +8, framingYearly:trialYes +6. Compute all four cell means. Does the trial help more with monthly or with yearly framing?
(LC6.5) After a significant interaction in a 2 × 3 design, why are pairwise comparisons of the six cells with ordinary t-tests a problem, and what does emmeans do about it?
(LC6.6) Which statements about mediation analysis are correct?
(LC6.7) An analyst wants to estimate the total effect of a loyalty program on annual spending and includes “number of store visits” — which the program itself increases — as a control variable. What does the coefficient of the program estimate now, and what should the analyst do to get the total effect?
(LC6.8) A colleague tests the effect of a new checkout page in 25 customer segments and reports that it “works particularly well for returning customers on tablets” (p = 0.02). What is the problem, and what would you recommend for the next test?
(LC6.9) Your group project experiment compares two versions of a product description. Name one plausible moderator and one plausible mediator for your effect, and explain for each when you would measure it in the questionnaire.