5  Learning from Observational Data

Driving question: What if we cannot randomize?

Experiments are the gold standard for causal questions — but most marketing data were never collected in an experiment. Customers choose which features they use, which channels they buy through, and which ads they click. Companies set prices and budgets in response to the market, not by coin flip. This chapter is about learning from such observational data: how far regression analysis can take us toward causal answers, where it stops, and what it is good for even when it cannot deliver causal conclusions. After working through this chapter you will be able to:

The chapter continues the story of the streaming service from Chapters 3 and 4. Session 5 covers Section 5.1 to Section 5.6; session 6 covers Section 5.7 to Section 5.11.

5.1 Motivation: Smart Mix without randomization

In Chapter 4, the streaming service tested Smart Mix in an A/B test with 400 users and found an increase in listening time of about 3 hours per month. Now imagine a different history: the company skipped the experiment and simply launched Smart Mix as an opt-in feature. Every user could switch it on. After four weeks, the analytics team pulls the data of 2,000 users: 653 of them adopted Smart Mix, 1347 did not.

Show how the data are loaded
library(tidyverse)
smartmix_obs <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/smartmix_obs.csv")
Table 5.1: The observational Smart Mix data (simulated)
Variable Description
smart_mix 1 if the user switched Smart Mix on, 0 otherwise
hours Listening hours in the four weeks after the launch
prior_hours Listening hours in the month before the launch
tenure Months since the user signed up
premium 1 for Premium subscribers, 0 for free users
device Main device: iOS, Android, or Desktop
age Age in years
churn 1 if the user cancelled within three months after the launch
upgraded 1 if a free user upgraded to Premium within three months (NA for Premium users)

The comparison the dashboard shows is dramatic (Figure 5.1): adopters listened 9.3 hours more than non-adopters — three times the effect found in the experiment.

Figure 5.1: The naive comparison in the observational data: listening hours of adopters and non-adopters of Smart Mix.

You know from Chapter 1 what to suspect. Nobody assigned Smart Mix by coin flip; users chose it — and the users who switch on a new music feature are not a random sample of all users. Figure 5.2 confirms the suspicion with data: adopters already listened 6.7 hours more before Smart Mix existed.

Figure 5.2: Listening hours in the month before the launch, by later adoption of Smart Mix. Dashed lines: group means.

The situation is the one from Figure 1.6, in a new costume (Figure 5.3): an unobserved variable — call it music enthusiasm — drives both the decision to adopt Smart Mix and the listening time. The naive comparison mixes the effect of Smart Mix with the effect of enthusiasm.

Figure 5.3: Why the naive comparison overstates the effect: enthusiasm drives both adoption and listening.

In an experiment, randomization cuts the dashed arrows. Without an experiment, we have one tool left: adjustment. If we can measure the variables that drive adoption — or good proxies for them — we can compare adopters and non-adopters who are alike on these variables, and isolate what is left. The tool for doing this is regression analysis, and the rest of the chapter develops it: first as a way of describing relationships (Section 5.2 and Section 5.3), then as a way of adjusting (Section 5.4), and finally with an honest look at what it cannot do.

5.2 From correlation to a line

5.2.1 The correlation coefficient

Regression starts with a question you can answer by looking: how does one variable change with another? Figure 5.6 plots listening hours after the launch against listening hours before it. The cloud slopes upward: users who listened a lot before also listen a lot now. The correlation coefficient \(r\) summarizes this in one number. It is the covariance of the two variables, standardized by their standard deviations:

\[ r = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_i (x_i - \bar{x})^2} \sqrt{\sum_i (y_i - \bar{y})^2}} \]

The numerator adds up, over all users \(i\), the product of the two deviations from the means: it is positive when users above the mean in \(x\) tend to be above the mean in \(y\) as well, negative when they tend to be below, and close to zero when the two deviations are unrelated. The denominator removes the units, so that \(r\) always lies between −1 and +1 (Figure 5.4):

  • the sign gives the direction: positive, the variables move together; negative, one goes up when the other goes down;
  • the size gives the strength of the linear association: \(r\) = ±1 means that all points lie exactly on a straight line, \(r\) = 0 means no linear association; as a rough convention, values around 0.1, 0.3, and 0.5 are called small, medium, and large associations;
  • \(r\) has no units and does not change when the variables are rescaled (hours or minutes, euros or cents), which makes correlations comparable across variables and studies.
Figure 5.4: Simulated data with correlation coefficients from −0.9 to +0.95: the sign gives the direction, the size the tightness of the cloud around a straight line.

Two caveats. First, \(r\) measures linear association only: Figure 5.5 shows a clear relationship with a correlation of almost zero, because the relationship is not a straight line. Always look at the scatter plot. Second, \(r\) is symmetric and says nothing about causation — you met this in Chapter 1: two variables can be correlated because one causes the other, because a third variable drives both, or by selection.

Figure 5.5: A strong but non-linear relationship. The correlation coefficient is close to zero, and so is the slope of the fitted line.

For the Smart Mix data, \(r\) = 0.64: a large positive association between listening before and after the launch.

cor(smartmix_obs$prior_hours, smartmix_obs$hours)
[1] 0.6397

Correlation and regression are not the same tool. The table summarizes the difference that the rest of the chapter builds on:

Table 5.2: Correlation vs. regression
Correlation Regression
Estimated coefficient \(r\), bounded between −1 and +1, no units \(\beta_1\), a priori not bounded, in units of \(y\) per unit of \(x\)
Interpretation Linear association between two variables; bidirectional (\(r_{xy} = r_{yx}\)) (Linear) relation of one or more predictors to an outcome; directional (\(x\) explains \(y\))
Role of theory Neither required nor testable Required (which variable is the outcome, which predictors belong in the model) and testable

A correlation says that and how tightly two variables move together. A regression says how much \(y\) changes with \(x\) — which presupposes a direction, and that is where theory, and the assumptions of Section 5.4, come in.

5.2.2 Two variables, one line

Figure 5.6: Listening hours after vs. before the launch, with the regression line.

A correlation says that the variables move together; the regression line says how much. It describes the average listening time after the launch as a straight-line function of the listening time before:

\[ \text{hours}_i = \beta_0 + \beta_1 \, \text{prior hours}_i + \varepsilon_i \]

The index \(i\) stands for a user: the equation holds for every one of the 2,000 users, with the same \(\beta_0\) and \(\beta_1\) for all of them and a different \(\varepsilon_i\) for each. \(\beta_0\) is the intercept (the predicted value when the predictor is zero), \(\beta_1\) the slope (by how much the outcome changes when the predictor increases by one unit), and \(\varepsilon_i\) the error term or residual — everything the line does not explain about user \(i\). In R:

coef(lm(hours ~ prior_hours, data = smartmix_obs))
(Intercept) prior_hours 
     6.7849      0.7291 

Every additional hour of listening before the launch goes with 0.73 additional hours after it. Note the wording: goes with, not causes. The line describes the association in the data, nothing more.

5.2.3 Which line? The least-squares idea

Many lines could run through a cloud of points. The regression line is the one that makes the sum of the squared residuals — the squared vertical distances between the points and the line — as small as possible (Figure 5.7). Formally, the ordinary least squares (OLS) estimator chooses the intercept and the slope that minimize

\[ \sum_{i=1}^{n} \hat{\varepsilon}_i^2 = \sum_{i=1}^{n} \left( y_i - \hat{\beta}_0 - \hat{\beta}_1 x_i \right)^2 \]

where \(y_i\) is user \(i\)’s listening time after the launch and \(x_i\) before it, and the hats mark estimates computed from the data. Squaring makes large misses count much more than small ones and treats misses above and below the line alike. This is what lm() (“linear model”) computes — and what you minimize by hand in the widget below.

Figure 5.7: Three candidate lines through the same 25 users. Orange segments are the residuals; the least-squares line makes their squared sum as small as possible.
TipTry it: fit the line yourself

Move the intercept and the slope and watch the residuals (orange) and their squared sum. Try to find the best line — then click the button to see the least-squares solution.

What to look for. Every change of the line makes some residuals smaller and others larger. The least-squares line is the compromise that minimizes their squared sum — no other straight line gets below it.

The covariance measures how two variables vary together: the average product of their deviations from their means, \(\text{cov}(x, y) = \frac{1}{n-1} \sum (x_i - \bar{x})(y_i - \bar{y})\). Its size depends on the units of \(x\) and \(y\); the correlation removes the units by dividing by both standard deviations: \(r = \text{cov}(x, y) / (s_x s_y)\), so that \(r\) always lies between −1 and +1.

The least-squares slope is the covariance divided by the variance of the predictor, \(\hat{\beta}_1 = \text{cov}(x, y) / s_x^2 = r \cdot s_y / s_x\), and the intercept makes the line pass through the point of means: \(\hat{\beta}_0 = \bar{y} - \hat{\beta}_1 \bar{x}\). Correlation and regression slope therefore carry the same information about the direction of the association; the slope adds the units (“hours per hour”), the correlation adds comparability across variables.

5.3 Reading a regression

The complete output of lm() contains more than the two coefficients. Let us read it for the simplest version of the Smart Mix question — a regression of listening hours on the adoption dummy:

model_naive <- lm(hours ~ smart_mix, data = smartmix_obs)
summary(model_naive)

Call:
lm(formula = hours ~ smart_mix, data = smartmix_obs)

Residuals:
   Min     1Q Median     3Q    Max 
-20.88  -7.64  -2.06   4.76 101.22 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   17.541      0.300    58.5   <2e-16 ***
smart_mix      9.341      0.525    17.8   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 11 on 1998 degrees of freedom
Multiple R-squared:  0.137, Adjusted R-squared:  0.136 
F-statistic:  316 on 1 and 1998 DF,  p-value: <2e-16

Table 5.3 walks through the parts that matter. The two coefficients are read as follows: the intercept (17.54) is the predicted listening time when all predictors are zero — here the mean of the non-adopters; the coefficient of smart_mix (9.34) is the change in listening time for a one-unit increase in the predictor, which for a 0/1 variable is the step from 0 to 1: adopters minus non-adopters. The general rule holds for every regression in this chapter: a coefficient is the change in the outcome when its predictor increases by one unit and nothing else changes — for a continuous predictor such as prior_hours (0.73 hours per additional prior hour), for a dummy (the difference between the two groups), and, with several predictors, “holding the other variables in the model constant” (Section 5.4).

Table 5.3: How to read the output of lm()
Output Meaning
Estimate The coefficients: the intercept (17.54) is the mean listening time of non-adopters; the coefficient of smart_mix (9.34) is the difference between adopters and non-adopters
Std. Error The standard error of each coefficient — its uncertainty, exactly as in Chapter 3
t value, Pr(>|t|) The t-test of each coefficient against zero and its p-value — the same test as in Chapter 4 (signal divided by noise)
Residual standard error The typical size of a residual: how far individual users are from the line, in hours
Multiple R-squared The share of the variation in the outcome that the model explains — here 14%
F-statistic A test of the whole model against a model with no predictors (relevant with several predictors)

Two observations connect this to what you already know. First, with a single 0/1 predictor, the regression is the comparison of two means: the coefficient of smart_mix equals the difference in means from Figure 5.1, and its t-test is the two-sample t-test of Chapter 4 (assuming equal variances). Second, the confidence interval of a coefficient is built as always — estimate ± about 2 standard errors — and R gives it with confint():

confint(model_naive)
             2.5 % 97.5 %
(Intercept) 16.953  18.13
smart_mix    8.311  10.37

R² — the share of explained variation. You met this idea in Chapter 4: the ANOVA splits the total variation of the outcome into the part explained by the groups and the residual part, and \(\eta^2\) is the explained share. R² is the same quantity for a regression line, \(R^2 = SS_M / SS_T\): the share of the variation in \(y\) that the line explains, between 0 and 1. For the naive model it is 0.137 — whether a user has Smart Mix explains 14% of how differently users listen; for the line through prior listening it is 0.41. Figure 5.8 shows what the number means: the same line, with less and less scatter around it.

Figure 5.8: The same regression line with different amounts of scatter around it (simulated data). The orange segments are the residuals; the less of the variation is left in them, the higher R².

R² describes how well the line fits; it says nothing about whether the slope is a causal effect, and a small R² does not make an effect unimportant (Smart Mix explains 14% of the variation, yet 9 hours is a large difference). For reporting, round the coefficient table to three decimals: round(coef(summary(model_naive)), 3).

R² compares the residuals of the model with the residuals of the most basic model, which predicts the mean for everybody: \(R^2 = 1 - \text{SS}_\text{residual} / \text{SS}_\text{total}\). A value of 0.14 means that the model’s predictions are 14% “better” (in squared error) than simply guessing the mean. R² never decreases when you add a predictor, even a useless one; the adjusted R² reported next to it includes a small penalty for each predictor and is the better number for comparing models with different numbers of predictors.

The F-test asks whether the model as a whole explains more than chance — the same logic as the ANOVA in Chapter 4: variation explained by the model per degree of freedom, divided by unexplained variation per degree of freedom. With one predictor, it is equivalent to the t-test of that predictor.

Standardized coefficients express each effect in standard deviations (“one SD more prior listening goes with 0.6 SD more listening now”). They make coefficients of variables with different units comparable in size. You get them by standardizing the variables before the regression, e.g., lm(scale(hours) ~ scale(prior_hours), data = smartmix_obs).

5.4 Adjusting for confounders

5.4.1 Several predictors at once

The naive regression tells us how adopters and non-adopters differ. To ask how they would differ if they had the same listening history, we add that history to the model. A multiple regression fits a line — more precisely, a plane — through several predictors at once:

\[ \text{hours} = \beta_0 + \beta_1 \times \text{smart mix} + \beta_2 \times \text{prior hours} + \varepsilon \]

model_prior <- lm(hours ~ smart_mix + prior_hours, data = smartmix_obs)
summary(model_prior)

Call:
lm(formula = hours ~ smart_mix + prior_hours, data = smartmix_obs)

Residuals:
   Min     1Q Median     3Q    Max 
-29.98  -5.52  -1.38   4.15  90.19 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)    6.451      0.412    15.7   <2e-16 ***
smart_mix      4.901      0.443    11.1   <2e-16 ***
prior_hours    0.662      0.020    33.2   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.85 on 1997 degrees of freedom
Multiple R-squared:  0.443, Adjusted R-squared:  0.443 
F-statistic:  795 on 2 and 1997 DF,  p-value: <2e-16

The coefficient of smart_mix has dropped from 9.3 to 4.9 hours. Its interpretation has changed too: it is now the difference between adopters and non-adopters with the same prior listening time — the effect of Smart Mix “holding prior listening constant”. This is what adjustment means: the regression compares like with like, at least with respect to the variables in the model. Because adopters listened more before the launch, and prior listening predicts current listening, part of the naive difference was due to prior listening — and that part is now attributed to prior_hours instead of to Smart Mix.

The same logic extends to more variables. Each coefficient in a multiple regression is the association between its variable and the outcome holding all other variables in the model constant:

model_full <- lm(hours ~ smart_mix + prior_hours + tenure + premium + device, data = smartmix_obs)
summary(model_full)

Call:
lm(formula = hours ~ smart_mix + prior_hours + tenure + premium + 
    device, data = smartmix_obs)

Residuals:
   Min     1Q Median     3Q    Max 
-30.38  -5.21  -1.26   4.10  90.22 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)     6.2547     0.5404   11.58  < 2e-16 ***
smart_mix       4.4724     0.4375   10.22  < 2e-16 ***
prior_hours     0.6126     0.0206   29.69  < 2e-16 ***
tenure          0.0377     0.0113    3.34  0.00084 ***
premium         2.9243     0.4257    6.87  8.6e-12 ***
deviceAndroid  -1.4750     0.4223   -3.49  0.00049 ***
deviceDesktop  -2.4880     0.5759   -4.32  1.6e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.67 on 1993 degrees of freedom
Multiple R-squared:  0.466, Adjusted R-squared:  0.464 
F-statistic:  290 on 6 and 1993 DF,  p-value: <2e-16

Tenure, Premium status, and the device change little: the estimate settles at about 4.5 hours. Figure 5.9 lines the estimates up against the benchmark from the experiment.

Figure 5.9: The estimated effect of Smart Mix: naive, adjusted for more and more observed variables, and the randomized experiment from Chapter 4. The true effect in the simulated data is 3 hours.

5.4.2 What adjustment can and cannot do

Figure 5.9 carries the central lesson of this chapter. Adjustment helped a lot: it removed about 77% of the bias of the naive comparison. But it did not remove all of it. The adjusted estimate of 4.5 hours is still above the true effect of 3 hours, and its confidence interval does not even contain it. The reason is visible in Figure 5.3: the confounder is enthusiasm, and we do not observe enthusiasm. We observe prior_hours, a proxy for it — a good proxy, but an imperfect one. Regression removes exactly the part of the confounding that our variables capture, and leaves the rest.

TipTry it: how good must a proxy be?

The simulation below creates 2,000 users with an unobserved enthusiasm that drives both the adoption of Smart Mix and listening hours. The true effect of Smart Mix is +3 hours. You cannot observe enthusiasm, but you observe a proxy for it — and you choose how good that proxy is. The chart compares the naive estimate with the estimate adjusted for the proxy.

What to look for. With a perfect proxy (100%), adjustment recovers the true effect. With a 50% proxy, half of the bias remains. With no proxy (0%), adjusting does nothing — the “adjusted” estimate is as wrong as the naive one. And the stronger the confounding, the more the quality of the proxy matters.

Two further warnings belong here:

  • Adjusting for the wrong variables makes things worse. If a variable lies on the causal path from treatment to outcome — a mediator (Chapter 1) — adjusting for it removes part of the effect you want to measure. Figure 5.10 shows why. Suppose Smart Mix increases listening partly by making users discover new artists. In the regression of hours on Smart Mix alone, both paths are open and the coefficient is the total effect. Adding “number of new artists discovered” as a control compares adopters and non-adopters who discovered the same number of artists — the indirect path is blocked, and the coefficient shows only the direct part. Only confounders — variables that influence both the treatment and the outcome, and are determined before the treatment — belong in the adjustment set. (Chapter 6 uses this blocking deliberately, to measure the indirect part.)
Figure 5.10: Adjusting for a mediator blocks the indirect part of the effect: the coefficient of Smart Mix then measures only the direct part.
  • No data set can tell you whether you have adjusted for enough. The assumption that there are no unobserved confounders left is untestable (Chapter 1). The honest way to present an adjusted estimate is therefore with a statement of what was adjusted for, and what plausibly was not.

A multiple regression does not literally compare users with identical prior listening. What it does is equivalent to a two-step procedure: first, remove from both the outcome and the treatment everything that the other predictors can explain (regress each on the other predictors and keep the residuals); then regress the residualized outcome on the residualized treatment. The coefficient from that simple regression is the multiple-regression coefficient. “Holding constant” therefore means “using only the part of the variation in the treatment that is unrelated to the other predictors”.

This also explains why correlated predictors are a problem: if two predictors move almost in lockstep, little independent variation is left for either, and both coefficients become imprecise (large standard errors). The variance inflation factor (VIF) quantifies this; car::vif(model_full) computes it, and values above about 5 deserve attention. Collinearity does not bias the coefficients — it makes them uncertain.

5.4.3 Where the unobserved variable goes

The whole of this section rests on one assumption, and it is worth seeing exactly where it comes from. Take the simplest version of the problem, with a cause, an outcome, and one unobserved variable — the price of a product, its sales, and the weather, which lowers prices in slow seasons and raises sales in good ones (Figure 5.11). The true model has three ingredients:

\[ \text{sales}_i = \beta_0 + \beta_1 \, \text{price}_i + \beta_2 \, \text{weather}_i + \phi_i \]

where \(\phi_i\) collects everything else. If the weather is not in the data, we can only estimate

\[ \text{sales}_i = \beta_0 + \beta_1 \, \text{price}_i + \varepsilon_i, \qquad \varepsilon_i = \beta_2 \, \text{weather}_i + \phi_i \]

The omitted variable does not disappear: it moves into the error term. That alone would be harmless — error terms are full of omitted things. The problem is that the weather also drives the price, so the error term is now correlated with the regressor. Least squares cannot tell the two apart and attributes the weather’s effect on sales to the price: \(\hat{\beta}_1\) is biased, and it stays biased however large the sample becomes. This is the omitted-variable bias of Chapter 1, written as an equation.

Figure 5.11: The structure behind omitted-variable bias: the unobserved variable drives both the cause and the outcome.

Figure 5.12 shows the same idea in a scatter plot. The observed variation in price has two components. Part of it is exogenous: prices that moved for reasons unrelated to the weather (a cost change, a pricing experiment), and the demand response to that part is the causal effect — downward. Part of it is endogenous: prices that moved with the weather, together with demand — upward, but not because of the price. The observed cloud mixes the two, and the fitted line is a mixture too. Everything this chapter does — adjustment here, difference-in-differences in Section 5.10 — and everything Chapter 4 did with randomization amounts to isolating the exogenous part of the variation.

Figure 5.12: Observed variation = exogenous + endogenous variation (simulated data). Only the exogenous part identifies the causal effect of price on demand; the endogenous part comes from the weather moving both.

5.4.4 The assumption: exogeneity

In general form, with \(y_i = \beta_0 + \beta_1 x_i + \varepsilon_i\), the coefficient \(\beta_1\) is the causal effect of \(x\) only if the regressor is unrelated to the error term:

\[ \text{Cov}(x_i, \varepsilon_i) = 0 \]

This condition is called exogeneity — the variable of interest is determined “from outside” the model, not by the same forces that sit in the error term. It is the most important assumption of the linear model when the goal is an effect rather than a prediction. If it fails, \(x\) is endogenous, the estimate is biased and inconsistent (more data do not cure it), and \(\beta_1\) cannot be read as causal. In an experiment, randomization guarantees exogeneity: a coin flip is unrelated to everything. In the opt-in data, it fails: enthusiasm drives adoption and is part of \(\varepsilon_i\). Every adjustment variable we add moves a piece of the error term into the model: prior_hours took most of the enthusiasm out of \(\varepsilon_i\), which is why the estimate dropped from 9.3 to 4.5 hours; what is left in the error term still correlates with adoption, which is why 4.5 is still above 3.

The uncomfortable part: exogeneity cannot be tested in the data. The residuals of a fitted regression are uncorrelated with the predictors by construction — least squares makes them so — so the data always “look” exogenous. Whether the assumption holds has to be argued from outside the data: from theory, from what you know about how the data came to be (who chose the treatment, and why), and from the data-generating process you can draw as a DAG. The remedies are the ones of this course: include the uncontrolled factor or a good proxy for it, randomize, or find a quasi-experiment (Section 5.10). Instrumental variables, the econometrician’s further tool for endogenous regressors, are beyond this course.

5.5 Categorical predictors

The model above already contains two categorical predictors, and their coefficients deserve a closer look. A 0/1 variable such as premium enters the model directly: its coefficient (2.9) is the difference in listening hours between Premium subscribers and free users, holding everything else constant.

A categorical variable with several categories, such as device with the levels iOS, Android, and Desktop, cannot be entered as a single number — the categories have no order. R handles this automatically: it chooses one category as the reference (by default the first level of the factor, here iOS) and creates a 0/1 variable — a dummy — for each of the other categories:

coef(model_full)[c("deviceAndroid", "deviceDesktop")]
deviceAndroid deviceDesktop 
       -1.475        -2.488 

Each dummy coefficient is the difference between its category and the reference category: Android users listen 1.5 hours less than iOS users, Desktop users 2.5 hours less — again holding the other variables constant. The p-values test whether each category differs from the reference, not whether the variable matters at all; for the latter, compare the model with and without the variable (anova(model_without, model_full)), which is the ANOVA of Chapter 4 in regression form.

The reference category is a matter of convenience, not of substance; the model is the same regardless of which category serves as the baseline. Choose the category that makes the comparisons you care about: smartmix_obs$device <- relevel(smartmix_obs$device, ref = "Android") makes Android the reference, so that the coefficients compare iOS and Desktop with Android. A variable stored as text ("iOS", "Android", …) is converted to a factor automatically, with the levels in alphabetical order — which is why it pays to set the levels yourself (Chapter 2).

5.6 Prediction vs. explanation

So far we have used regression to explain: to estimate the effect of one variable while holding others constant. Regression is at least as useful for predicting — and the two uses have different rules.

Suppose the service wants to predict the listening time of users in order to plan server capacity or to target retention offers. For this predictive question (Chapter 1), it does not matter why a variable is associated with listening time, only that it is. Prior listening, tenure, Premium status, device, and Smart Mix adoption can all go into the model, confounded or not. What matters is how well the predictions hold up for new users — users the model has not seen. The standard check is to split the data: fit the model on a training set and evaluate it on a test set:

set.seed(42)
train_ids <- sample(nrow(smartmix_obs), 1500)
train <- smartmix_obs[train_ids, ]
test  <- smartmix_obs[-train_ids, ]

model_pred <- lm(hours ~ prior_hours + tenure + premium + device + smart_mix, data = train)
test$predicted <- predict(model_pred, newdata = test)

In-sample vs. out-of-sample fit. The R² reported by summary() is computed on the training data — the same users the line was fitted to — and therefore flatters the model. The honest counterpart is the out-of-sample R²: how much of the variation in the test users’ listening time the predictions capture. The simplest version is the squared correlation between predicted and actual values in the test set:

summary(model_pred)$r.squared                  # in-sample R-squared (training data)
[1] 0.4817
cor(test$predicted, test$hours)^2              # out-of-sample R-squared (test data)
[1] 0.4235

Here the two are close (0.48 vs. 0.42): the model has few predictors and 1,500 training users, so it has learned little noise. With many predictors or small samples, the gap widens — that is overfitting made visible.

The typical prediction error. For a decision maker, a percentage of explained variation is less useful than the question “how far off is a prediction, in hours?”. The root mean squared error answers it:

\[ \text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} \left( y_i - \hat{y}_i \right)^2} \]

Take every test user’s prediction error \(y_i - \hat{y}_i\), square it (so that over- and under-predictions do not cancel, and large misses count more), average the squares, and take the root to return to the original unit. The RMSE is the standard deviation of the prediction errors: a typical prediction misses by about this much.

sqrt(mean((test$hours - test$predicted)^2))   # RMSE: typical prediction error in hours
[1] 9.425
Figure 5.13: Predicted vs. actual listening hours for the 500 users in the test set. Points on the dashed line would be perfect predictions.

The model predicts a typical user to within about 9 hours — useful for capacity planning, even though the coefficient of smart_mix in this model is a biased estimate of its causal effect. A model can be a good predictor and a bad explainer at the same time, and vice versa.

ImportantTwo questions, two rules
  • Explanation (causal question): include confounders, exclude mediators, and be explicit about what is not observed. The coefficient of interest is what matters; R² is secondary.
  • Prediction (predictive question): include whatever predicts, and judge the model by its errors on data it has not seen. Coefficients are not interpreted; the predictions are what matters.

Mixing the two — reading causal effects off a model built for prediction, or judging a causal model by its R² — is one of the most common mistakes in applied analytics.

A model with many predictors fits its training data better and better, because it learns not only the patterns but also the noise of that particular sample. Its errors on new data then get worse: this is overfitting, and it is why predictive models are judged out of sample. Within the training data, adjusted R² and information criteria such as the AIC (AIC(model)) penalize each additional predictor and help to compare models of different size — the model with the lowest AIC balances fit and parsimony. They are useful for a first comparison, but they do not replace a test set.

TipCoding block (session 5): two cases

Case 1: podcast promotion. A podcast network tracks 400 episodes: the promotion spend for the episode (promo_spend, euros), the host’s followers (host_followers), and the downloads in the release week (downloads). The data are in podcast_promo.csv (section “Coding block 1” in the chapter’s R script).

  1. Draw a scatter plot of downloads (y) against promotion spend (x), and compute the correlation. Describe the relationship in one sentence.
  2. Fit the regression of downloads on promotion spend with lm() and look at summary(): interpret the slope in words, and read off the R².
  3. Is the slope a causal effect of promotion? What would you need to argue?

Case 2: a loyalty program. An online shop lets customers opt into its loyalty program. The data set loyalty_program.csv contains 1,500 customers: membership (member, 1/0), spending this year (spending, euros), spending in the previous year (spend_prev), tenure in years, and the main device (device).

  1. Naive comparison: regress spending on member. Interpret the coefficient — and say why it is probably not the causal effect of the program.
  2. Adjustment: add spend_prev, tenure, and device. How does the member coefficient change, and what does it mean now? Report it with its 95% confidence interval.
  3. Interpret the coefficient of device.
  4. Is membership exogenous after adjustment? Argue from the data-generating process: who joins a loyalty program, and is everything that drives this in the model?

The solutions will be available after the session.

5.7 Functional form: when the straight line is wrong

5.7.1 Two assumptions of the linear model

Every regression so far has been a linear, additive model, \(y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + \dots + \varepsilon_i\), and such a model makes two assumptions about how the predictors work:

  • Linearity: the effect of a one-unit change in a predictor is the same regardless of the predictor’s level — constant marginal returns. An increase in advertising from 10 € to 11 € adds as many sales as an increase from 100,000 € to 100,001 €. There is no saturation.
  • Additivity: the effect of one predictor does not depend on the values of the other predictors. Each playlist placement adds the same number of streams whether the artist has 1,000 followers or a million.

Both assumptions are convenient — the model is easy to estimate and to read — and both are questionable for most marketing relationships. This section relaxes the first with the multiplicative (log-log) model, which has diminishing returns built in; the same model also relaxes the second, because in it the effect of each predictor scales with the others. Chapter 6 relaxes additivity in a second way, with interaction terms, which let the effect of one variable depend explicitly on another. And Section 5.9 shows how to detect a wrong functional form in the residuals of a fitted model.

5.7.2 Diminishing returns

Regression draws straight lines, but marketing relationships are rarely straight. The second data set of this chapter contains 500 promotion campaigns for new releases at the streaming service: the promotion spend, the number of playlist placements the campaign secured, the artist’s followers, and the streams in the first four weeks.

Show how the data are loaded
campaigns <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/campaigns.csv")

How do streams respond to promotion spend? The left panel of Figure 5.14 shows the problem with a straight line: the first euros of promotion buy many streams, later euros fewer — diminishing returns. A straight line cannot bend; it overestimates streams for small budgets and underestimates them in the middle. The right panel shows the cure: on logarithmic scales for both axes, the cloud becomes a straight line again.

Figure 5.14: Streams and promotion spend for 500 campaigns. Left: original scale with a linear and a log-log fit. Right: the same data on log-scaled axes (the units stay euros and streams; each gridline is ten times the previous one) — the cloud becomes a straight line.

Marginal returns, step by step. Figure 5.15 makes the difference between the two fits concrete. In the linear model, every additional €6,000 of promotion buys the same number of streams — about 34,000 — whether the campaign starts from €3,000 or from €24,000: constant marginal returns, and the effect of spend is added to whatever else the campaign has. In the multiplicative model, the same €6,000 buys about 45,000 streams at a small budget but only 12,000 at a large one: decreasing marginal returns, because spend scales the streams — its effect is a percentage of what is already there. The two models also read their coefficient differently: in the linear model, one more unit of \(x\) adds \(\beta_1\) units of \(y\) (5.6 streams per euro); in the multiplicative model, one percent more \(x\) adds \(\beta_1\) percent of \(y\) (0.38% of streams per 1% of spend — the elasticity introduced below).

Figure 5.15: What one more step of spend buys. Left: the linear model — each additional €6,000 buys the same number of streams. Right: the multiplicative model — each step buys fewer streams than the last.

Both models are estimated with lm() — the multiplicative one after taking logs, as the next subsection explains. Their outputs side by side:

model_lin_simple <- lm(streams ~ spend, data = campaigns)
summary(model_lin_simple)

Call:
lm(formula = streams ~ spend, data = campaigns)

Residuals:
    Min      1Q  Median      3Q     Max 
-204459  -67186  -34157   27654  694356 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 92600.025   6782.260   13.65   <2e-16 ***
spend           5.589      0.781    7.16    3e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 114000 on 498 degrees of freedom
Multiple R-squared:  0.0932,    Adjusted R-squared:  0.0914 
F-statistic: 51.2 on 1 and 498 DF,  p-value: 3.01e-12
model_loglog_simple <- lm(log(streams) ~ log(spend), data = campaigns)
summary(model_loglog_simple)

Call:
lm(formula = log(streams) ~ log(spend), data = campaigns)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.2804 -0.5076  0.0152  0.5652  2.3720 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   8.2098     0.3094    26.5   <2e-16 ***
log(spend)    0.3841     0.0375    10.2   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.802 on 498 degrees of freedom
Multiple R-squared:  0.174, Adjusted R-squared:  0.173 
F-statistic:  105 on 1 and 498 DF,  p-value: <2e-16

The linear model explains 9% of the variation in streams, the log-log model 17% of the variation in log streams. The two R² values are not strictly comparable, because the outcomes differ, but a gap this large in the same direction as the residual plots of Section 5.9 is good evidence that the curved shape fits the data better — and it is one of the criteria for choosing a specification: fit, the residual plot, and above all the plausibility of the assumed shape for the marketing instrument at hand.

5.7.3 The log-log model and elasticities

Diminishing returns are what a multiplicative model produces. Instead of adding up the contributions of the predictors, it multiplies them:

\[ \text{streams}_i = e^{\beta_0} \cdot \text{spend}_i^{\,\beta_1} \cdot \text{followers}_i^{\,\beta_2} \cdot e^{\varepsilon_i} \]

Each additional euro of spend now adds a percentage of the current streams rather than a fixed number — a power smaller than one bends the curve exactly as in Figure 5.14. Taking the logarithm of both sides turns the product into a sum, and the model becomes a linear regression again, the log-log model:

\[ \log(\text{streams}_i) = \beta_0 + \beta_1 \log(\text{spend}_i) + \beta_2 \log(\text{followers}_i) + \varepsilon_i \]

Three rules of logarithms do the work: \(\log(a \cdot b) = \log a + \log b\) (a product becomes a sum), \(\log(a^b) = b \log a\) (a power becomes a factor), and \(\log(e^x) = x\). Applied to the multiplicative model: \(\log(e^{\beta_0} \cdot \text{spend}^{\beta_1} \cdot \text{followers}^{\beta_2} \cdot e^{\varepsilon})\) = \(\beta_0 + \beta_1 \log(\text{spend}) + \beta_2 \log(\text{followers}) + \varepsilon\). Compare the two worlds: in the additive level-level model, \(\text{streams}_i = \beta_0 + \beta_1 \text{spend}_i + \dots\), each euro adds \(\beta_1\) streams regardless of anything else; in the multiplicative model, the effect of spend is scaled by the followers and by the current level of streams. The log transformation is what lets lm() estimate the multiplicative model: we fit a straight line to the logged variables and read the coefficients as powers of the original ones.

model_loglog <- lm(log(streams) ~ log(spend) + log(followers) + placements + genre, data = campaigns)
summary(model_loglog)

Call:
lm(formula = log(streams) ~ log(spend) + log(followers) + placements + 
    genre, data = campaigns)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.5962 -0.2684  0.0284  0.3030  1.4799 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)          2.8815     0.2346   12.28  < 2e-16 ***
log(spend)           0.3310     0.0207   16.00  < 2e-16 ***
log(followers)       0.5071     0.0157   32.28  < 2e-16 ***
placements           0.1203     0.0119   10.07  < 2e-16 ***
genreHipHop/Rap      0.1994     0.0476    4.19 0.000033 ***
genreRock           -0.2555     0.0599   -4.27 0.000023 ***
genreElectro/Dance   0.1026     0.0594    1.73    0.085 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.44 on 493 degrees of freedom
Multiple R-squared:  0.754, Adjusted R-squared:  0.751 
F-statistic:  251 on 6 and 493 DF,  p-value: <2e-16

The coefficient of log(spend) has a special interpretation: it is an elasticity. A 1% increase in promotion spend goes with a 0.33% increase in streams; a 10% increase with about 3.3%. The elasticity is constant along the curve — which is exactly what makes the multiplicative model fit diminishing returns: 10% more spend always buys the same percentage of additional streams, but at a high budget 10% is a lot of money for the same percentage. Elasticities are the natural language of marketing response: they do not depend on units, and they are comparable across variables, markets, and studies. The followers elasticity of 0.51, for example, says that the artist’s existing audience matters more than the promotion budget.

5.7.4 Why the log transformation straightens the curve

Figure 5.16 shows the mechanics. In a multiplicative model, equal percentage steps in spend produce equal percentage steps in streams: each doubling of the budget adds the same percentage to streams, but at a higher budget that percentage is added to a larger base, so the number of additional streams shrinks. On the original scale this traces a curve that flattens out. The logarithm turns multiplication into addition — a step of +100% in \(x\) is always the same distance of \(\log 2\) on the log axis, and a step of +32% in \(y\) the same distance of \(\log 1.32\) — so equal percentage steps become equal distances, and the curve becomes a straight line whose slope is the elasticity.

Figure 5.16: Why the log transformation works. Left: each doubling of spend adds the same percentage to streams, but fewer and fewer streams. Right: on log scales, equal percentage steps are equal distances — a straight line with slope 0.4.

Both. The log-log model is additive in the logarithms: the percentage effect of spend does not depend on the number of followers — 10% more spend buys 3.3% more streams for a small and a large artist alike. But it is multiplicative in the levels: 3.3% of a large artist’s streams is many more streams than 3.3% of a small artist’s, so in absolute terms the effect of spend is scaled by the follower base (and by everything else in the model). Compared with the level-level model, in which each euro adds the same number of streams for everyone, the additivity assumption is relaxed in levels and kept in percentages. If you believe that percentage effects also depend on other variables — that promotion is relatively more effective for small artists, say — you need an interaction term in the log-log model, which is the subject of Chapter 6.

5.7.5 Elasticities: constant in the log-log model, not in the linear one

The elasticity of \(y\) with respect to \(x\) is the percentage change in \(y\) per percent change in \(x\):

\[ \eta_x = \frac{\Delta y / y}{\Delta x / x} = \frac{\Delta y}{\Delta x} \cdot \frac{x}{y} \]

It is the unit-free way of stating how responsive sales are to a marketing instrument. The two models treat it very differently (Figure 5.17):

  • In the linear model, the marginal effect \(\Delta y / \Delta x = \beta_1\) is constant, so the elasticity \(\eta_x = \beta_1 \cdot x / y\) rises with \(x\): advertising becomes relatively more effective the more of it you buy — the opposite of saturation, and implausible for most marketing instruments.
  • In the multiplicative model, \(\Delta y / y = \beta_1 \cdot \Delta x / x\), so the elasticity is the constant \(\beta_1\) and the marginal effect falls with \(x\) — diminishing returns, which is what the campaign data show.
Figure 5.17: Sales and the elasticity of sales with respect to advertising in the two models. Linear: constant marginal returns, rising elasticity. Multiplicative: diminishing returns, constant elasticity.

5.7.6 What the elasticity tells you about the shape

The value of \(\beta_1\) in the multiplicative model \(y = e^{\beta_0} x^{\beta_1}\) determines the shape of the response curve (Figure 5.18):

  • \(\beta_1 < 0\): \(y\) falls with \(x\), steeply at first and then ever more slowly — the typical shape of a price response.
  • \(0 < \beta_1 < 1\): \(y\) rises with diminishing returns — the typical shape for advertising, promotion, and distribution; most marketing elasticities lie here, usually well below 0.5.
  • \(\beta_1 = 1\): \(y\) is proportional to \(x\) — doubling spend doubles streams. The response curve is then a straight line through the origin, so for this one value the multiplicative and the linear model describe the same mean response. The models still differ in everything else: the multiplicative model has no intercept (no sales without spend), its errors are multiplicative, and the other predictors scale the effect.
  • \(\beta_1 > 1\): increasing returns — the curve bends upward: each additional euro buys more than the previous one. Rare in marketing. It occurs with network effects, where the product becomes more valuable the more people use it (a messaging app or a marketplace is worth little with ten users and a lot with ten million, so each new user is worth more than the last), and with threshold phenomena, where a promotion starts to spread by word of mouth once it has reached a critical mass.
Figure 5.18: The response curve of the multiplicative model for different values of the elasticity.

Two further properties follow from the form. A multiplicative model is not defined for \(x\) = 0 (the logarithm of zero does not exist — see the box on zeros below), and it has no minimum level of the outcome: with zero spend it predicts zero streams, whereas the linear model’s intercept acts as a baseline. The properties of the two models side by side:

Table 5.4: Properties of the linear and the multiplicative model
Linear (level-level) Multiplicative (log-log)
Estimation OLS directly OLS after taking logs
Marginal returns Constant Diminishing (for \(0 < \beta_1 < 1\)); saturation possible
Elasticity Rises with \(x\) Constant (\(\beta_1\)) — simple to communicate and to use for budget decisions
Effects of several predictors Add up Scale each other (additive in logs)
Baseline Intercept = outcome at \(x\) = 0 No minimum level; not defined at \(x\) = 0
Optimal level of the instrument Zero (price) or infinite (advertising) Finite, found by comparing elasticities with costs

5.7.7 Marketing mix models

What we just estimated is a small marketing mix model (MMM): a regression of a performance outcome (sales, streams, sign-ups) on the marketing inputs that are supposed to drive it (advertising spend by channel, promotions, price, distribution) and on control variables (seasonality, competitors). Many companies use such models to answer the question behind every marketing budget: where does the next euro do the most good? The multiplicative, log-log form is the workhorse of this literature because it delivers exactly what the budget question needs — an elasticity per channel, i.e., the percentage change in sales per percent of additional spend, with diminishing returns built in. With elasticities for several channels, the budget can be reallocated toward the channels where a euro buys the largest percentage gain, until the marginal returns are equal across channels.

Two things make real marketing mix models more complex than our campaign example. Advertising works with a delay and wears out slowly, so models include carryover (“adstock”) terms for past spend; and channels interact and saturate, so the functional form is often richer than a constant elasticity. But the core logic is the one of this section, and so is the core problem of this chapter: a marketing mix model is estimated from observational data. Budgets are not set at random — they go up before a product launch, in the peak season, and in markets where sales are expected to grow — so spend is endogenous in exactly the sense of Section 5.4, and the estimated elasticities can overstate what advertising really does. This is why companies increasingly combine marketing mix models with experiments — the geo-experiments and holdout tests of Chapter 1 — to calibrate the elasticities on causal ground.

5.7.8 Four ways to combine levels and logs

Logging the outcome, a predictor, both, or neither gives four model types with four interpretations (Table 5.5, Figure 5.19).

Table 5.5: Functional forms and how to read their coefficients
Model Equation Interpretation of \(\beta_1\)
Level-level \(y = \beta_0 + \beta_1 x\) One more unit of \(x\) → \(\beta_1\) more units of \(y\)
Log-level \(\log(y) = \beta_0 + \beta_1 x\) One more unit of \(x\) → about \(100 \cdot \beta_1\)% more \(y\) (exactly: \(100 \cdot (e^{\beta_1} - 1)\)%); a semi-elasticity
Level-log \(y = \beta_0 + \beta_1 \log(x)\) 1% more \(x\) → about \(\beta_1 / 100\) more units of \(y\)
Log-log \(\log(y) = \beta_0 + \beta_1 \log(x)\) 1% more \(x\) → about \(\beta_1\)% more \(y\) (an elasticity)
Figure 5.19: The four shapes: constant change, constant percentage growth, diminishing absolute returns, and constant elasticity.

The model above contains a log-level term as well: placements enters in levels while the outcome is logged. Its coefficient of 0.12 means that each additional playlist placement goes with about 12% more streams — exactly, 12.8%. For coefficients up to about 0.1, the approximation “\(100 \cdot \beta\) percent” is good enough; for larger ones, use the exact formula. The genre dummies are read the same way: a HipHop/Rap campaign reaches about 22% more streams than a Pop campaign with the same spend, followers, and placements.

Which form to choose? Let the data and the question decide: look at the scatter plot and the residuals (Section 5.9), and ask whether the relationship is more plausibly additive (“each placement adds 10,000 streams”) or multiplicative (“each placement adds 12%”). For outcomes such as sales, streams, or revenue, which are skewed and can only be positive, the logged outcome is usually the better default.

Zeros. The logarithm of zero is not defined, so a variable with zeros (campaigns without any spend, songs without any streams) cannot be logged directly. The common fix is log(x + 1); it changes little for large values and keeps the zeros in the data. For an outcome with many zeros, better models exist (e.g., count models), but log(y + 1) is the pragmatic first step — and it is what the difference-in-differences analysis in Section 5.10 uses.

Exact vs. approximate. In a model with a logged outcome, a coefficient \(\beta\) on an unlogged predictor means that one more unit multiplies the outcome by \(e^{\beta}\). For small \(\beta\), \(e^{\beta} - 1 \approx \beta\), hence the rule “\(100 \cdot \beta\) percent”. For \(\beta\) = 0.12 the exact change is 12.7%; for \(\beta\) = 0.5 it is already 64.9%, not 50%.

TipTry it: linear or log-log?

The simulation draws 300 campaigns from a world in which streams respond to spend with a constant elasticity that you set. Both a linear and a log-log model are fitted. Watch how well each follows the data as the elasticity changes — and read the elasticity off the log-log slope.

What to look for. Below an elasticity of 1, returns diminish and the linear line misses the curve at both ends. At exactly 1, the relationship is proportional and both models agree. Above 1, returns increase — rare in marketing, but it happens with network effects.

5.8 Yes/no outcomes: logistic regression

5.8.1 Why not a straight line?

Many outcomes are yes/no: did the user churn, click, buy, upgrade? The Smart Mix data record for every free user whether they upgraded to Premium within three months after the launch (upgraded); 22% did. Does listening time predict an upgrade? A regression of such a 0/1 outcome on listening hours fits a straight line through a cloud of zeros and ones (Figure 5.20, orange). It can be read as a model of the probability of an upgrade, but it produces probabilities below zero for light listeners and above one for heavy listeners — impossible values — and it misses the shape of the data: the share of upgrades (dark dots) rises slowly at first, steeply in the middle, and flattens out near 100% at the top.

Figure 5.20: Upgrades and listening hours among free users: a linear probability model (orange) and a logistic model (blue). Dark dots are the observed upgrade shares per 5-hour bin.

5.8.2 The logistic function

Instead of a straight line, we need a function that only takes values between 0 and 1. The logistic function does this:

\[ P(y_i = 1) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_i)}} \]

where \(e\) is the base of the natural logarithm. The expression \(\beta_0 + \beta_1 x_i\) is the familiar straight line — but instead of being the prediction itself, it is fed through the logistic function, which squeezes any number onto the interval between 0 and 1. When the line is far below zero (a light listener, in our example), \(e^{-(\dots)}\) is huge and the probability is close to 0; when the line is exactly zero, the probability is exactly 0.5; when the line is far above zero, \(e^{-(\dots)}\) vanishes and the probability is close to 1. In between, the function traces the S-curve of Figure 5.20. The function is derived from the log-odds: the odds of an event are the probability of the event divided by the probability of the non-event, \(P / (1 - P)\) — a probability of 0.2 corresponds to odds of 0.25, or “1 to 4”. Logistic regression assumes that the logarithm of the odds is a linear function of the predictors,

\[ \log \left( \frac{P(y_i = 1)}{1 - P(y_i = 1)} \right) = \beta_0 + \beta_1 x_i \]

Exponentiating both sides gives the odds, \(\frac{P(y_i = 1)}{1 - P(y_i = 1)} = e^{\beta_0 + \beta_1 x_i}\), and solving for \(P\) gives the logistic function above. The logarithm stretches the odds over the whole number line, so that a linear function can never produce impossible probabilities. Logistic regression is this model with the same ingredients as before — one or more predictors, the idea of holding the others constant — and a different link between the predictors and the outcome. In R, glm() (“generalized linear model”) with family = binomial:

free_users <- filter(smartmix_obs, premium == 0)
model_upgrade <- glm(upgraded ~ hours, family = binomial, data = free_users)
summary(model_upgrade)

Call:
glm(formula = upgraded ~ hours, family = binomial, data = free_users)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)  -4.5167     0.2438   -18.5   <2e-16 ***
hours         0.1629     0.0108    15.1   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1306.74  on 1238  degrees of freedom
Residual deviance:  926.39  on 1237  degrees of freedom
AIC: 930.4

Number of Fisher Scoring iterations: 5

The chart that goes with the model is the 0/1 outcome plotted against the predictor with the fitted logistic curve on top. ggplot2 can fit the curve directly: geom_smooth() with method = "glm" and the binomial family draws exactly the curve that glm() estimates (Figure 5.21).

ggplot(free_users, aes(x = hours, y = upgraded)) +
  geom_jitter(width = 0, height = 0.03, alpha = 0.15) +
  geom_smooth(method = "glm", method.args = list(family = binomial), se = FALSE) +
  labs(x = "Listening hours", y = "Upgraded to Premium (0/1)")
Figure 5.21: The upgrade outcome against listening hours (jittered points) with the logistic curve fitted by glm().

There is no line and no residual to square, so logistic regression cannot use least squares. It uses maximum likelihood instead: for given coefficients, the model assigns every user a probability of upgrading, \(P_i\); the likelihood of the data is the probability of observing exactly the upgrades and non-upgrades we saw, \(\prod_i P_i^{\,y_i} (1 - P_i)^{\,1 - y_i}\) — users who upgraded contribute \(P_i\), users who did not contribute \(1 - P_i\). The estimates \(\hat{\beta}_0\) and \(\hat{\beta}_1\) are the values that make this product (or, more conveniently, its logarithm) as large as possible: the coefficients under which the observed data would have been most likely. There is no formula for the maximum; glm() finds it by iteration, which is why the output reports a number of “Fisher Scoring iterations”. The standard errors, z-values, and p-values in the output are read like those of lm(); the t-distribution is replaced by the normal distribution.

Weak and strong effects. The slope coefficient \(\beta_1\) determines how steep the S-curve is, and therefore how well the predictor separates the two outcomes (Figure 5.22). A \(\beta_1\) close to zero gives an almost flat curve: the probability of an upgrade is nearly the same for light and heavy listeners, and listening time tells us little about who upgrades. A large \(\beta_1\) gives a curve that jumps from near 0 to near 1 within a few hours: knowing a user’s listening time almost determines whether they upgrade — the predictor discriminates strongly between upgraders and non-upgraders. The intercept \(\beta_0\) shifts the curve left or right; the midpoint, where the probability is 0.5, lies at \(x = -\beta_0 / \beta_1\) (here about 28 hours).

Figure 5.22: Three logistic curves with the same midpoint and different slope coefficients: the larger the coefficient, the more sharply listening time separates upgraders from non-upgraders.

5.8.3 Reading the coefficients

The coefficient of hours, 0.163, is the change in the log-odds of an upgrade per additional listening hour — a scale nobody has an intuition for. Three things can be read directly, however: the sign (positive: more listening, higher probability), the significance (p < 0.001), and, after exponentiating, the odds ratio:

exp(coef(model_upgrade))
(Intercept)       hours 
    0.01093     1.17689 

\(e^{\hat{\beta}_1}\) = 1.18: for each additional listening hour, the odds of an upgrade are 1.18 times as high, i.e., they increase by 18% — and this factor is the same everywhere on the curve. Odds ratios are common in research reports, but they are easily misread as ratios of probabilities (they are not, unless the event is rare).

For managers, probabilities are the better language, and predict() with type = "response" returns them for any value of the predictor:

predict(model_upgrade, newdata = data.frame(hours = c(10, 11, 20, 21, 30, 31, 40, 41)), type = "response")
      1       2       3       4       5       6       7       8 
0.05275 0.06151 0.22111 0.25043 0.59135 0.63005 0.88062 0.89671 

A free user who listens 10 hours a month has an upgrade probability of about 5%; at 30 hours it is 59%. Now compare each value with the value one hour later (Figure 5.23): from 10 to 11 hours, the probability rises by 0.9 percentage points; from 20 to 21 by 2.9; from 30 to 31 by 3.9; from 40 to 41 by 1.6. The same coefficient — the same odds ratio of 1.18 — translates into a different change in probability depending on where on the curve the user is: small at the flat ends, largest in the steep middle, around a probability of 50%. This is the characteristic property of the logistic model, and the reason why “the effect of one more hour” has no single answer in percentage points.

Figure 5.23: The predicted probability of an upgrade, and the change from one more listening hour at four points on the curve. The odds ratio is the same everywhere; the change in probability is not.

Three ways to report the size of an effect, then: the odds ratio (one number, constant, but hard to interpret), predicted probabilities at chosen values (e.g., 10 vs. 30 hours), and the average effect across all users — the mean difference in predicted probabilities when the variable is changed by one unit for everybody. As with lm(), confint() gives confidence intervals for the coefficients; exponentiating them gives intervals for the odds ratios:

exp(confint(model_upgrade))
               2.5 %  97.5 %
(Intercept) 0.006661 0.01734
hours       1.152949 1.20296

5.8.4 Several predictors

Everything extends to several predictors exactly as in Section 5.4: each coefficient describes the association with the log-odds, holding the other variables constant. For example, churn records whether a user cancelled within three months after the launch (16.9% did):

model_churn <- glm(churn ~ hours + premium + tenure + smart_mix, family = binomial, data = smartmix_obs)
summary(model_churn)

Call:
glm(formula = churn ~ hours + premium + tenure + smart_mix, family = binomial, 
    data = smartmix_obs)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)  0.27712    0.16136    1.72  0.08590 .  
hours       -0.06066    0.00851   -7.13    1e-12 ***
premium     -0.53299    0.15278   -3.49  0.00049 ***
tenure      -0.02045    0.00375   -5.45    5e-08 ***
smart_mix   -0.25635    0.16234   -1.58  0.11432    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1817.2  on 1999  degrees of freedom
Residual deviance: 1635.0  on 1995  degrees of freedom
AIC: 1645

Number of Fisher Scoring iterations: 5

Listening hours, Premium, and tenure clearly matter; Smart Mix adoption does not, once the others are held constant. The average effect of Premium status in percentage points:

p_free    <- predict(model_churn, newdata = mutate(smartmix_obs, premium = 0), type = "response")
p_premium <- predict(model_churn, newdata = mutate(smartmix_obs, premium = 1), type = "response")
mean(p_premium - p_free)
[1] -0.06477

Premium subscribers are about 6.5 percentage points less likely to churn than otherwise identical free users. (Whether this is a causal effect of the subscription is, of course, the same question as in Section 5.4: exogeneity is required here too.)

There is no R² for a logistic regression, because there are no squared residuals. The usual substitute is McFadden’s pseudo-R², which compares the log-likelihood of the model with that of a model without predictors: \(1 - \log L_{\text{model}} / \log L_{\text{null}}\). The performance package computes it with r2_mcfadden(model_upgrade) (by hand: 1 - model_upgrade$deviance / model_upgrade$null.deviance); for the upgrade model it is 0.29. Values are much lower than those of a linear R²; 0.2 to 0.4 already indicates a good fit. For prediction, the share of correctly classified users (with a cutoff of 0.5) or the area under the ROC curve are the more practical measures.

5.9 The diagnostics that change decisions

Textbooks list many assumptions of the linear model, and R can produce a whole battery of diagnostic plots and tests. Three checks are worth doing every time, because each can change a conclusion.

1. Is the straight line the right shape? Plot the residuals against the fitted values (Figure 5.24). If the residuals show a pattern — a curve, a U-shape — the model misses something systematic, and a different functional form (Section 5.7) or an additional predictor is needed. For the campaign data, the linear model leaves a clear curve in the residuals; the log-log model does not.

Figure 5.24: Residuals against fitted values for the linear and the log-log campaign model. A curved pattern means the model has the wrong shape.
plot(model_loglog, which = 1)   # residuals vs. fitted, with a smooth line

2. Does a handful of observations drive the result? A single extreme observation can tilt a regression line (Figure 5.25). Such influential observations are often data errors (Chapter 2) or genuinely different cases (one campaign with a viral hit). Look for them with plot(model, which = 5), and refit the model without them: if the conclusion changes, say so.

Figure 5.25: One influential observation can change the slope substantially.

3. Is the uncertainty right? The standard errors of lm() assume that the residuals scatter equally at all levels of the prediction. When the scatter grows with the fitted values — a funnel in the residual plot (Figure 5.26), common for sales and revenues — the coefficients remain unbiased, but their standard errors, and hence the p-values and confidence intervals, are wrong. A formal check is the Breusch–Pagan test (bptest() in the lmtest package), which tests whether the squared residuals depend on the predictors; a small p-value says they do. For the linear campaign model it rejects decisively, for the log-log model it does not. The fix is cheap either way: robust standard errors, which do not rely on this assumption:

Figure 5.26: A funnel in the residual plot of the linear campaign model: the scatter grows with the fitted values (heteroskedasticity).
library(sandwich)
library(lmtest)
model_linear <- lm(streams ~ spend + followers + placements, data = campaigns)
bptest(model_linear)                                   # heteroskedasticity test

    studentized Breusch-Pagan test

data:  model_linear
BP = 107, df = 3, p-value <2e-16
coeftest(model_linear, vcov = vcovHC(model_linear, type = "HC1"))   # robust standard errors

t test of coefficients:

              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 14779.4333 11620.8620    1.27  0.20404    
spend           5.4337     0.6869    7.91  1.7e-14 ***
followers       0.3408     0.0985    3.46  0.00058 ***
placements  16299.9818  2934.3428    5.55  4.5e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Often, the funnel disappears when the outcome is logged — another reason why the log-log model is the better default for skewed outcomes.

Influence is measured by Cook’s distance, which combines how far an observation lies from the others in the predictors with how badly the model fits it: cooks.distance(model); values far above the others (a common rule: above 4/n, or above 1) deserve a look. Heteroskedasticity can be tested formally with the Breusch–Pagan test, lmtest::bptest(model), but the robust standard errors are the practical answer either way — many analysts use them by default.

Two classic diagnostics are not on the list above. Normality of the residuals matters little with the sample sizes of this course, thanks to the central limit theorem (Chapter 3); a Q-Q plot (plot(model, which = 2)) is worth a glance for extreme outliers, not for its own sake. And multicollinearity affects the precision of coefficients, not their validity (Section 5.4); it is a problem only when the coefficients of the correlated variables are what you need.

5.10 A quasi-experiment: difference-in-differences

5.10.1 Playlist listings as a natural experiment

Adjustment handles confounders you can measure. A second strategy for observational data uses time: if we observe the same units before and after an intervention, and a comparison group that did not receive it, we can net out everything that stays constant within units and everything that changes for everyone. This is the difference-in-differences (DiD) logic you met in Chapter 1 with the Spotify study. Here we apply it to real data.

The question: what does a listing on a major Spotify playlist do to a song’s streams? The data contain weekly streams of 290 songs over 21 weeks. In the week of March 19, 2018, 53 of them were added to a large playlist (the treated songs); the other 237 were not (the control songs). The data are real, from a research project at WU.

Show how the data are loaded
playlist <- read_csv("https://raw.githubusercontent.com/wu-rds/MA2026/main/data/playlist_did.csv")
Table 5.6: The playlist data
Variable Description
song_id, week One row per song and week (21 weeks: 10 before, the listing week, 10 after)
streams Weekly streams of the song
treated 1 for songs added to the playlist, 0 for control songs
post 1 for weeks after the listing, 0 for weeks before
genre, major_label, playlist_followers Song and artist characteristics

Figure 5.27 shows the average (log) streams of both groups over time. Three things stand out. First, the playlisted songs start at a higher level — they are not a random sample of songs, so a simple comparison of levels would be misleading. Second, before the listing, both groups move in parallel: whatever drives weekly streams (seasonality, platform-wide trends) affects both groups alike. Third, at the listing, the treated group jumps.

5.10.2 Two differences, one estimate

The DiD estimate uses four numbers: the mean outcome of each group before and after the intervention (Figure 5.28). The first difference — after minus before — captures the change in each group; the difference between these differences is the effect, because the control group’s change estimates what would have happened to the treated songs without the listing:

\[ \text{DiD} = (\bar{y}_{\text{treated, after}} - \bar{y}_{\text{treated, before}}) - (\bar{y}_{\text{control, after}} - \bar{y}_{\text{control, before}}) \]

Figure 5.28: The four means behind the difference-in-differences estimate (listing week excluded). The dotted line is the counterfactual: the treated songs’ before-level, shifted by the control songs’ change.
did_data <- playlist |>
  filter(week != as.Date("2018-03-19")) |>          # drop the listing week itself
  mutate(log_streams = log(streams + 1))

did_data |>
  group_by(treated, post) |>
  summarise(mean_log_streams = mean(log_streams), .groups = "drop")
# A tibble: 4 × 3
  treated  post mean_log_streams
    <dbl> <dbl>            <dbl>
1       0     0             9.76
2       0     1             9.72
3       1     0             9.85
4       1     1            10.1 

By hand: (10.09 − 9.85) − (9.72 − 9.76) = 0.28 log points.

5.10.3 The DiD regression

The same estimate comes out of a regression with three terms — the treatment group dummy, the post-period dummy, and their product:

\[ \log(\text{streams}_{it}) = \beta_0 + \beta_1 \, \text{treated}_i + \beta_2 \, \text{post}_t + \beta_3 \, (\text{treated}_i \times \text{post}_t) + \varepsilon_{it} \]

Here \(i\) indexes the song and \(t\) the week: treated varies between songs, post between weeks, and the outcome and the error term vary over both.

model_did <- lm(log_streams ~ treated * post, data = did_data)
summary(model_did)

Call:
lm(formula = log_streams ~ treated * post, data = did_data)

Residuals:
   Min     1Q Median     3Q    Max 
-6.207 -0.463 -0.025  0.572  3.601 

Coefficients:
             Estimate Std. Error t value  Pr(>|t|)    
(Intercept)    9.7622     0.0179  545.86   < 2e-16 ***
treated        0.0913     0.0418    2.18     0.029 *  
post          -0.0456     0.0253   -1.80     0.071 .  
treated:post   0.2796     0.0592    4.73 0.0000023 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.871 on 5796 degrees of freedom
Multiple R-squared:  0.0142,    Adjusted R-squared:  0.0137 
F-statistic: 27.8 on 3 and 5796 DF,  p-value: <2e-16

In R, treated * post is shorthand for treated + post + treated:post. Each coefficient has a clear meaning (Table 5.7), and the one we care about is the interaction treated:post: 0.28 log points, i.e., the playlist listing increased weekly streams by about 32% — exactly the by-hand estimate, now with a standard error and a confidence interval (0.16 to 0.4).

Table 5.7: The coefficients of the DiD regression
Coefficient Value Meaning
(Intercept) 9.76 Control songs, before: the baseline level
treated 0.09 Treated songs, before: how much higher they already were — the level difference between the groups
post -0.05 Control songs, after minus before: the common time trend
treated:post 0.28 The extra change of the treated songs — the DiD effect

The regression form has two advantages over the four means: it gives the uncertainty, and it extends naturally — control variables, several periods, or several treatment groups can be added. (The interaction term that does the work here is the subject of Chapter 6, where it appears in its general role.)

5.11 What observational data can and cannot tell you

This chapter equipped you with two strategies for causal questions without randomization, and with a tool that is useful regardless of causality. (For a deeper, still readable treatment of these strategies, Angrist and Pischke (2009) remains the standard reference.)

  • Adjustment (Section 5.4) handles confounders you can measure. It is only as good as your variables: with a perfect proxy for the confounder, it recovers the truth; with no proxy, it changes nothing. The assumption behind it — exogeneity, the treatment is uncorrelated with everything left in the error term — can never be tested in the data; it has to be argued from theory and from how the data came to be.
  • Difference-in-differences (Section 5.10) handles confounders that are constant over time, measured or not — but it requires parallel trends, which the pre-period can make plausible but never prove.
  • Prediction (Section 5.6) needs no causal assumptions at all. A regression that predicts well is valuable even if none of its coefficients can be interpreted as an effect.

Whichever strategy you use, report it the way Chapter 4 taught: the effect, its uncertainty, and — for observational data — the assumptions it rests on. “Adjusting for prior listening, tenure, Premium status, and device, adopters listen about 4.5 hours more (95% CI 3.6 to 5.3). This estimate assumes that no further differences between adopters and non-adopters affect listening — an assumption that the experiment in Chapter 4, which found 3.2 hours, suggests is not fully met.”

The regression toolkit has one more use, which the next chapter develops: it can tell us for whom an effect is larger (moderation, through interaction terms like the one in the DiD regression) and through which mechanism it works (mediation). That is the subject of Chapter 6.

Learning check

(LC5.1) In a regression of listening hours on prior listening hours, the slope is 0.83. Interpret the coefficient in one sentence — and explain why it does not show that listening before the launch causes listening after it.

Users who listened one hour more in the month before the launch listened, on average, 0.83 hours more in the four weeks after it. The coefficient describes an association: it compares different users with different listening histories, not the same user with more or less prior listening. Both variables are driven by the same characteristics of a user — enthusiasm for music, free time, a Premium subscription — so prior listening predicts later listening without causing it. A causal reading would require that prior listening is unrelated to everything else that drives current listening (exogeneity, Section 5.4), and nothing suggests that here: nobody assigned listening histories at random.

(LC5.2) Which statements about adjustment in multiple regression are correct?

Correct: statements 1, 2, and 4. Statement 2: what happens depends on how the added variable is related to the other predictor and to the outcome. The coefficient of Smart Mix fell from 9.3 to 4.9 hours when prior listening was added, because prior listening goes with both adoption and listening time; a variable that is unrelated to the predictor of interest leaves its coefficient almost unchanged; and a variable that works against the predictor of interest can make its coefficient larger. Statement 3 is wrong for two reasons. Adjustment removes only the part of the confounding that the observed variables capture — the fully adjusted estimate of 4.5 hours is still above the true effect of 3 hours, because enthusiasm is not observed. And “all available variables” may include variables that must not be adjusted for. Statement 4 names the most important of them: a mediator lies on the causal path, and holding it constant blocks the indirect part of the effect (Figure 5.10).

(LC5.3) A model contains the categorical variable plan with the levels “Free”, “Premium”, and “Family” (reference: Free). The coefficient of planFamily is 4.2. Interpret it. How would you test whether the plan matters at all?

Users on the Family plan have an outcome that is 4.2 units higher than that of users on the Free plan — the reference category — holding the other variables in the model constant (4.2 listening hours, if the outcome is listening hours). The coefficient says nothing about the difference between Family and Premium: that is the difference between the two dummy coefficients, or the coefficient you get after making Premium the reference with relevel().

The p-values of the two dummies test each plan against Free, not the variable as a whole. To test whether the plan matters at all, compare the model with and without the variable: anova(model_without, model_with) tests both dummy coefficients at once with an F-test (Section 5.5).

(LC5.4) A colleague fits a regression with 25 predictors to 300 customers and reports R² = 0.71 for predicting next month’s spending. What should you ask before trusting this number?

Whether the R² was computed in-sample or out-of-sample. An R² that is computed on the same 300 customers the model was fitted to flatters the model: with 25 predictors and only 300 observations, the model has plenty of room to fit the noise of this particular sample (overfitting), and R² never falls when a predictor is added. Ask for the performance on customers the model has not seen — a test set — and for the typical prediction error in euros (the RMSE), which says more to a decision maker than a share of explained variation (Section 5.6).

A good second question is how the 25 predictors were chosen. If they were picked because they correlated with spending in these same data, even the in-sample number is too optimistic. The adjusted R² and the AIC penalize the number of predictors and help with a first comparison, but they do not replace the test set.

(LC5.5) In a log-log regression, the coefficient of log(advertising spend) is 0.15. (a) Interpret it. (b) The same analysis in levels gives a coefficient of 0.8 sales per euro. Why might the two models reach different conclusions about whether a large increase in the advertising budget pays off?

Part (a): the coefficient is an elasticity. A 1% increase in advertising spend goes with about 0.15% more sales, a 10% increase with about 1.5% — at every level of the budget. An elasticity between 0 and 1 means diminishing returns.

Part (b): the two models make different assumptions about the shape of the response. The linear model assumes constant marginal returns: every additional euro brings 0.8 units of sales, the hundred-thousandth as much as the first, so a large increase of the budget looks as profitable per euro as a small one. In the log-log model each additional euro brings less than the one before: doubling the budget raises sales by only \(2^{0.15} - 1 \approx\) 11%. A large increase can therefore pay off according to the linear model and not according to the log-log model. Which one to believe is a question of the functional form — saturation is the typical pattern for advertising, and the scatter plot and the residuals show which shape fits the data (Section 5.7, Section 5.9). And for both models: the coefficient is the effect of advertising only if spend is exogenous, which is doubtful when budgets follow expected sales.

(LC5.6) In a log-level model with the outcome log(sales), the coefficient of a dummy for “promotion week” is 0.35. By what percentage do sales differ in promotion weeks? Use both the approximate and the exact interpretation.

Approximately: \(100 \cdot 0.35\) = 35% higher sales in promotion weeks. Exactly: \(100 \cdot (e^{0.35} - 1)\) = 41.9%. The approximation is good for coefficients up to about 0.1; at 0.35 it is already seven percentage points off. Report the exact value: sales are about 42% higher in promotion weeks, holding the other variables in the model constant.

(LC5.7) Which statements about logistic regression are correct?

Correct: statements 1, 3, and 4. Statement 2 is wrong: a coefficient is a change in the log-odds, and its exponential is an odds ratio. The change in probability that goes with it depends on where on the S-curve an observation lies — small at the flat ends, largest around 50% (Figure 5.23). This is why effects are best reported as differences between predicted probabilities at chosen values (statement 3). Statement 4 is the reason for the model: the logistic function turns any value of the linear predictor into a probability between 0 and 1, whereas a straight line predicts probabilities below 0 and above 1.

(LC5.8) An analyst reports a difference-in-differences estimate of a price promotion on sales in treated stores. Which statements are correct?

Correct: statements 1, 3, and 4. Statement 2 is wrong: a difference in levels between the groups is harmless, because it is subtracted out — in the regression it is the coefficient of treated. The playlisted songs of Section 5.10 started far above the control songs. What the estimate needs is that both groups would have changed in the same way without the treatment (statement 3). Statement 4: the assumption is about what the treated stores would have done after the promotion started, without it — something that is never observed. Parallel trends before the promotion and a placebo test make the assumption plausible, not certain.

(LC5.9) The residual plot of a regression of revenue on advertising shows a funnel: the residuals scatter more widely for large fitted values. What does this mean for the coefficients and for the p-values — and what is the simplest fix?

The funnel is heteroskedasticity: the scatter around the line is not the same at all levels of the prediction. The coefficients remain unbiased. The standard errors that lm() reports, however, assume equal scatter and are wrong — and with them the p-values and the confidence intervals. The simplest fix is robust standard errors, which do not rely on this assumption: coeftest(model, vcov = vcovHC(model, type = "HC1")) with the packages sandwich and lmtest; the Breusch–Pagan test (bptest(model)) confirms the diagnosis (Section 5.9). For an outcome such as revenue it is also worth looking at the log-log model: a funnel often disappears when the outcome is logged.

(LC5.10) Your group project experiment randomizes two versions of a product description. Afterwards, you also want to know whether the effect differs between frequent and occasional buyers. Which tool from this chapter do you need — and in which chapter is it developed?

An interaction term: a regression of the outcome on the condition, on the type of buyer, and on their product, lm(outcome ~ condition * frequent_buyer). The coefficient of the interaction is the difference between frequent and occasional buyers in the effect of the description. It is the construction of the difference-in-differences regression (Section 5.10), where treated * post gave the difference between two differences; Chapter 6 develops it in its general role, as the tool for moderation.

Two things to settle before the data collection: ask about buying frequency before respondents see the description, so that the answer cannot be affected by it; and write down that you will test this difference — a difference between subgroups that you discover afterwards is an exploratory finding.

References

Angrist, Joshua D., and Jörn-Steffen Pischke. 2009. Mostly Harmless Econometrics: An Empiricist’s Companion. Princeton University Press.
Callaway, Brantly, and Pedro H. C. Sant’Anna. 2021. “Difference-in-Differences with Multiple Time Periods.” Journal of Econometrics 225 (2): 200–230.