Logistic regression with a binary and numeric predictor

1 A continuous moderator

In logistic regression with two binary predictors, baseline depression was grouped as below or at least 10 on the PHQ-9. That can be useful for a clearly defined clinical decision, but it also turns different scores into the same group. Here we retain the observed continuous phq9_screen score and ask:

How does the estimated probability of treatment response differ between therapist-guided treatment and waitlist at different baseline PHQ-9 scores?

A logistic regression interaction is an interaction on the log-odds scale. That detail matters: even an additive logistic model can have probability differences that vary with PHQ-9, because the logit-to-probability transformation is nonlinear. We therefore calculate contrasts on the probability scale rather than reading their shape from a coefficient table.

2 Packages and analytic data

library(tidyverse)
library(here)
library(marginaleffects)

options(
  marginaleffects_print_omit = c("s.value"),
  marginaleffects_print_style = ifelse(interactive(), "summary", "tinytable")
)
df_binary <- read_csv2(here("data", "steps_clean.csv")) |>
  filter(!is.na(lsas_screen), !is.na(lsas_post)) |>
  mutate(
    # The second factor level is the event modeled by binomial glm().
    lsas_response = factor(
      if_else(
        (lsas_screen - lsas_post) / lsas_screen >= 0.30,
        "Response",
        "No response"
      ),
      levels = c("No response", "Response")
    ),
    trt = factor(
      trt,
      levels = c("waitlist", "therapist-guided", "self-guided")
    )
  ) |>
  filter(trt %in% c("waitlist", "therapist-guided")) |>
  drop_na(lsas_response, phq9_screen) |>
  droplevels()

phq_values <- c(5, 10, 15)

df_binary |>
  summarise(
    participants = n(),
    minimum_phq9 = min(phq9_screen),
    maximum_phq9 = max(phq9_screen)
  )
participants minimum_phq9 maximum_phq9
112 1 19

Response means a reduction of at least 30% from baseline LSAS. Waitlist is the treatment reference group, and Response is the event whose probability is modeled. We restrict this chapter to the waitlist and therapist-guided arms so that every treatment contrast has one clear direction.

3 Additive logistic model

3.1 What does “additive” mean here?

The additive model has a treatment term and a PHQ-9 term, but no product term:

\[ \operatorname{logit}\{P(Y_i = \text{Response} \mid trt_i, PHQ9_i)\} = \beta_0 + \beta_1\mathbf{1}\{trt_i = \text{therapist-guided}\} + \beta_2 PHQ9_i. \]

The therapist-guided versus waitlist log-odds difference is the same at every PHQ-9 score in this model. Equivalently, the treatment odds ratio is constant across PHQ-9. That is not the same as saying the probability difference is constant: a fixed change in log-odds maps to different probability changes near 0, 0.5, and 1.

mod_additive <- glm(
  lsas_response ~ trt + phq9_screen,
  family = binomial,
  data = df_binary
)

summary(mod_additive)

Call:
glm(formula = lsas_response ~ trt + phq9_screen, family = binomial, 
    data = df_binary)

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)    
(Intercept)         -1.68842    0.66201  -2.550   0.0108 *  
trttherapist-guided  2.42468    0.51322   4.724 2.31e-06 ***
phq9_screen         -0.04753    0.05270  -0.902   0.3671    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 142.11  on 111  degrees of freedom
Residual deviance: 111.43  on 109  degrees of freedom
AIC: 117.43

Number of Fisher Scoring iterations: 4

We can exponentiate the coefficients to express them on the odds-ratio scale. The treatment coefficient gives the odds ratio for therapist-guided treatment versus waitlist, adjusted for baseline PHQ-9. Because this model does not include an interaction, this treatment odds ratio is assumed to be the same at every baseline PHQ-9 score.

For PHQ-9, the coefficient represents the change in log-odds associated with a one-point increase in baseline PHQ-9. Exponentiating this coefficient therefore gives the odds ratio associated with a one-point higher PHQ-9 score, adjusted for treatment group.

b_additive <- coef(mod_additive)
exp(b_additive[["trttherapist-guided"]]) # OR therapist-guided vs waitlist
[1] 11.2986
exp(b_additive[["phq9_screen"]]) # OR for a one-point increase in PHQ-9
[1] 0.9535786

Thus, the estimated treatment OR is approximately 11.30, while the OR associated with a one-point increase in PHQ-9 is approximately 0.95.

As stated before, odds ratios can be difficult to translate into the actual probability of treatment response. We can therefore use the fitted model to estimate the treatment contrast directly on the probability scale. avg_comparisons() predicts each participant’s probability of response under therapist-guided treatment and under waitlist, calculates the difference between these probabilities, and then averages these differences across participants.

additive_trt_difference <- avg_comparisons(
  mod_additive,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "response"
)
additive_trt_difference
Estimate Std. Error z Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: response
0.461 0.0792 5.82 <0.001 0.306 0.616
additive_trt_or <- avg_comparisons(
  mod_additive,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "link",
  transform = exp
)
additive_trt_or
Estimate Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: link
11.3 <0.001 4.13 30.9

Averaged over the observed baseline PHQ-9 distribution, therapist-guided treatment is estimated to change the probability of treatment response by 46.1 percentage points compared with waitlist (95% CI 30.6 to 61.6 percentage points).

The conditional treatment OR, adjusted for PHQ-9, is 11.30 (95% CI 4.13 to 30.89).

This is therapist-guided minus waitlist; a positive value favors a higher estimated probability of response with therapist guidance. It is a marginal probability difference over this analysis sample, conditional on the additive model—not a coefficient interpreted as a percentage-point change.

plot_predictions(
  mod_additive,
  condition = c("phq9_screen", "trt")
) +
  labs(
    title = "Additive logistic model",
    subtitle = "Estimated probabilities with 95% confidence intervals",
    x = "Baseline PHQ-9 score",
    y = "Probability of treatment response",
    color = "Treatment group",
    fill = "Treatment group"
  ) +
  theme_minimal()

Additive-model estimated probabilities of treatment response, with 95% confidence intervals.

The curves need not be parallel on the probability scale. The additive model makes its parallel-lines assumption on the log-odds scale, not on this plot’s probability scale.

4 Interaction model

4.1 Let the treatment association vary with PHQ-9

The interaction model adds a product term:

\[ \begin{aligned} \operatorname{logit}\{P(Y_i = \text{Response} \mid trt_i, PHQ9_i)\} = &\ \beta_0 + \beta_1\mathbf{1}\{trt_i = \text{therapist-guided}\} + \\ &\ \beta_2 PHQ9_i + \beta_3\mathbf{1}\{trt_i = \text{therapist-guided}\} \times PHQ9_i. \end{aligned} \]

Now the treatment log-odds difference can change with PHQ-9. The treatment coefficient in summary() is the difference at PHQ-9 = 0, which is not a useful stand-alone clinical summary here. We instead estimate probability differences at realistic PHQ-9 scores with clinical relevance.

mod_interaction <- glm(
  lsas_response ~ trt * phq9_screen,
  family = binomial,
  data = df_binary
)

summary(mod_interaction)

Call:
glm(formula = lsas_response ~ trt * phq9_screen, family = binomial, 
    data = df_binary)

Coefficients:
                                Estimate Std. Error z value Pr(>|z|)  
(Intercept)                     -1.81866    1.02038  -1.782   0.0747 .
trttherapist-guided              2.60970    1.20900   2.159   0.0309 *
phq9_screen                     -0.03400    0.09493  -0.358   0.7202  
trttherapist-guided:phq9_screen -0.01944    0.11405  -0.170   0.8647  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 142.11  on 111  degrees of freedom
Residual deviance: 111.40  on 108  degrees of freedom
AIC: 119.4

Number of Fisher Scoring iterations: 4
# Store the coefficients for the calculations below
b_interaction <- coef(mod_interaction)
b_trt <- b_interaction[["trttherapist-guided"]]
b_trt_phq <- b_interaction[["trttherapist-guided:phq9_screen"]]

With an interaction in the model, the association between treatment and response is allowed to vary with baseline PHQ-9. This changes how we interpret the coefficients.

The treatment coefficient, 2.61, is the therapist-guided versus waitlist difference in log-odds when PHQ-9 = 0. Exponentiating it gives an odds ratio of approximately 13.6, but this is the treatment odds ratio specifically at PHQ-9 = 0 and is therefore not particularly informative for our clinical question.

The interaction coefficient tells us how the treatment difference on the log-odds scale changes with each one-point increase in PHQ-9. Here, the interaction coefficient is -0.019. This means that for each one-point increase in PHQ-9, the therapist-guided versus waitlist log-odds difference decreases by 0.019.

We can exponentiate the interaction coefficient:

exp(b_trt_phq)
[1] 0.9807504

This gives approximately 0.98. Thus, for every one-point increase in PHQ-9, the treatment odds ratio is multiplied by approximately 0.98. For example, the treatment odds ratio at PHQ-9 = 10 is:

exp(b_trt + b_trt_phq * 10)
[1] 11.19344

However, interpreting interactions through odds ratios quickly becomes cumbersome. It is usually easier to ask our substantive question directly: how much higher or lower is the estimated probability of treatment response with therapist-guided treatment at different PHQ-9 scores?

We can therefore estimate the therapist-guided versus waitlist probability and OR difference at selected PHQ-9 values:

conditional_trt_difference <- avg_comparisons(
  mod_interaction,
  variables = list(trt = c("waitlist", "therapist-guided")),
  newdata = datagrid(phq9_screen = phq_values),
  by = "phq9_screen",
  type = "response"
)
conditional_trt_difference
phq9_screen Estimate Std. Error z Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: response
5 0.508 0.1120 4.53 < 0.001 0.288 0.727
10 0.460 0.0799 5.76 < 0.001 0.304 0.617
15 0.409 0.1258 3.25 0.00116 0.162 0.655
conditional_trt_or <- avg_comparisons(
  mod_interaction,
  variables = list(trt = c("waitlist", "therapist-guided")),
  newdata = datagrid(phq9_screen = phq_values),
  by = "phq9_screen",
  type = "link",
  transform = exp
)
conditional_trt_or
phq9_screen Estimate Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: link
5 12.3 < 0.001 2.93 52.0
10 11.2 < 0.001 4.08 30.7
15 10.2 0.00385 2.11 48.9

At PHQ-9 = 5, therapist-guided minus waitlist is an estimated 50.8 percentage-point difference in the probability of treatment response (95% CI 28.8 to 72.7).

At PHQ-9 = 10, the corresponding difference is 46.0 percentage points (95% CI 30.4 to 61.7); at PHQ-9 = 15 it is 40.9 percentage points (95% CI 16.2 to 65.5).

Each contrast conditions on the displayed PHQ-9 value. Positive values mean a higher modeled probability with therapist-guided treatment.

The corresponding therapist-guided-versus-waitlist ORs are:

  • PHQ-9 = 5: 12.34 (95% CI 2.93 to 51.98);
  • PHQ-9 = 10: 11.19 (95% CI 4.08 to 30.74); and
  • PHQ-9 = 15: 10.16 (95% CI 2.11 to 48.92).
plot_predictions(
  mod_interaction,
  condition = c("phq9_screen", "trt")
) +
  labs(
    title = "Interaction logistic model",
    subtitle = "Estimated probabilities with 95% confidence intervals",
    x = "Baseline PHQ-9 score",
    y = "Probability of treatment response",
    color = "Treatment group",
    fill = "Treatment group"
  ) +
  theme_minimal()

Interaction-model estimated probabilities of treatment response, with 95% confidence intervals.

4.2 A curve of the conditional probability difference

The probability curves are useful, but they leave the reader to visually subtract two uncertain quantities. A direct contrast plot answers the treatment question more directly.

plot_comparisons(
  mod_interaction,
  variables = list(trt = c("waitlist", "therapist-guided")),
  condition = "phq9_screen",
  type = "response"
) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  labs(
    title = "Conditional treatment probability difference",
    subtitle = "Therapist-guided minus waitlist; 95% confidence intervals",
    x = "Baseline PHQ-9 score",
    y = "Probability difference (percentage points)"
  ) +
  scale_y_continuous(labels = scales::label_number(scale = 100, accuracy = 1)) +
  theme_minimal()

Conditional therapist-guided-minus-waitlist probability difference across baseline PHQ-9, with 95% confidence intervals.

The dashed zero line marks no modeled probability difference. Wide intervals at the edge of the observed PHQ-9 range are a reminder not to make subgroup claims from the curve’s point estimates alone.

5 Conditional and marginal treatment contrasts

A conditional contrast answers a question such as “what is the modeled difference at PHQ-9 = 10?” A marginal (population-averaged) contrast answers a different question: “what is the modeled treatment difference after averaging each participant’s counterfactual predictions over the observed PHQ-9 distribution?” We estimate it by marginal standardization, as in logistic regression foundations.

marginal_trt_difference <- avg_comparisons(
  mod_interaction,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "response"
)
marginal_trt_difference
Estimate Std. Error z Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: response
0.461 0.079 5.83 <0.001 0.306 0.616
# Odds ratio of the two average counterfactual probabilities
marginal_trt_or <- avg_comparisons(
  mod_interaction,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "response",
  comparison = "lnoravg",
  transform = exp
)
marginal_trt_or
Estimate Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: ln(odds(therapist-guided) / odds(waitlist))
Type: response
11.1 <0.001 4.06 30.4

Averaged over the observed PHQ-9 distribution, the interaction model estimates that therapist-guided treatment changes the probability of treatment response by 46.1 percentage points compared with waitlist (95% CI 30.6 to 61.6 percentage points).

This marginal contrast is not the effect at a particular PHQ-9 score. It averages each participant’s counterfactual predictions over the PHQ-9 values represented in this sample, then compares the averages, so it can change if the target population’s baseline PHQ-9 distribution changes.

The corresponding marginal treatment OR is 11.10 (95% CI 4.06 to 30.40). It is the ratio of odds calculated from the two average counterfactual probabilities, not the average of the conditional ORs above.

6 Non-collapsibility of the odds ratio

Adjusting for a covariate can change a treatment estimate for many reasons, e.g. by dealing with confounding. In a randomized trial, adjusting for a prognostic baseline covariate is commonly done to increase precision (U.S. Food and Drug Administration 2023; Morris et al. 2022). In a linear model of post-treatment LSAS, such adjustment leaves the treatment coefficient unchanged on average. Odds ratios behave differently: when the treatment has an effect, adjusting for a prognostic baseline covariate moves the odds ratio away from 1, on average, even in a perfectly balanced trial (Robinson and Jewell 1991; Daniel et al. 2021). This property is called non-collapsibility.

6.1 Collapsible and non-collapsible effect measures

An effect measure is collapsible if the effect in a whole population is a weighted average of the effects in its subgroups. The population effect then always lies between the smallest and largest subgroup effects, which is what most of us would expect of any effect measure. Risk differences and risk ratios behave this way. The odds ratio does not: the odds ratio in the whole population can lie outside the range of the subgroup odds ratios, even when nothing is confounded (Hernán and Robins 2020; Greenland et al. 1999).

The following made-up trial, adapted from Hernán and Robins (2020), shows what this means. Treatment is randomized among 400 participants, half with mild and half with severe symptoms, and severity strongly predicts response.

df_collapse <- tibble(
  severity = rep(c("mild", "severe"), each = 2),
  trt = rep(c("control", "treatment"), times = 2),
  n = 100,
  responders = c(40, 80, 20, 60)
)

# Risk difference, risk ratio, and odds ratio from the response proportions
effect_measures <- function(data) {
  data |>
    summarise(p = sum(responders) / sum(n), .by = trt) |>
    pivot_wider(names_from = trt, values_from = p) |>
    transmute(
      risk_difference = treatment - control,
      risk_ratio = treatment / control,
      odds_ratio = (treatment / (1 - treatment)) / (control / (1 - control))
    )
}

collapse_measures <- list(
  Mild = filter(df_collapse, severity == "mild"),
  Severe = filter(df_collapse, severity == "severe"),
  `Whole trial` = df_collapse
) |>
  map(effect_measures) |>
  list_rbind(names_to = "group")
collapse_measures
group risk_difference risk_ratio odds_ratio
Mild 0.4 2.000000 6.000000
Severe 0.4 3.000000 6.000000
Whole trial 0.4 2.333333 5.444444

In both severity groups, treatment increases the probability of response by 40 percentage points, and it does so in the whole trial as well. The risk ratio is 2 in the mild group and 3 in the severe group, and 2.33 in the whole trial, in between the two. The odds ratio is 6 in both groups, yet 5.44 in the whole trial: smaller than in either half. Severity is not a confounder, because treatment was randomized. And because the made-up trial is exactly balanced, with 100 participants in each cell, chance imbalance plays no role either, so the difference between the odds ratios is due to non-collapsibility alone. The reason lies in how the whole-trial proportions arise. Each whole-trial response proportion is an average of the subgroup proportions, because each severity group makes up half of each arm. The whole-trial risk difference is therefore the average of the subgroup risk differences. The whole-trial risk ratio is a weighted average of the subgroup risk ratios, so it lies between them. Odds are a nonlinear function of probability, so the whole-trial odds are not averages of the subgroup odds, and the whole-trial odds ratio need not lie between the subgroup odds ratios; this is the point made in logistic regression with a numeric predictor.

6.2 Conditional and marginal odds ratios in regression models

Regression models show the same thing. Adjusting for severity gives the odds ratio within severity groups, whereas the unadjusted model gives the odds ratio for the whole trial:

# One row per participant
df_collapse_long <- df_collapse |>
  reframe(
    response = rep(c(1, 0), c(responders, n - responders)),
    .by = c(severity, trt)
  ) |>
  mutate(trt = factor(trt, levels = c("control", "treatment")))

mod_collapse_unadjusted <- glm(
  response ~ trt,
  family = binomial,
  data = df_collapse_long
)
mod_collapse_adjusted <- glm(
  response ~ trt + severity,
  family = binomial,
  data = df_collapse_long
)

# Odds ratio from the coefficient, standardized odds ratio, and standardized
# risk difference for each model
summarise_collapse <- function(mod) {
  trt_contrast <- list(trt = c("control", "treatment"))
  tibble(
    or_coefficient = exp(coef(mod)[["trttreatment"]]),
    or_standardized = avg_comparisons(
      mod,
      variables = trt_contrast,
      comparison = "lnoravg",
      transform = exp
    )$estimate,
    rd_standardized = avg_comparisons(mod, variables = trt_contrast)$estimate
  )
}

collapse_models <- list(
  Unadjusted = mod_collapse_unadjusted,
  `Adjusted for severity` = mod_collapse_adjusted
) |>
  map(summarise_collapse) |>
  list_rbind(names_to = "model")
collapse_models
model or_coefficient or_standardized rd_standardized
Unadjusted 5.444444 5.444444 0.4
Adjusted for severity 6.000000 5.444444 0.4

The odds ratio from the treatment coefficient is 5.44 in the unadjusted model and 6.00 in the model adjusted for severity. Standardizing the adjusted model gives back the whole-trial odds ratio, 5.44. The standardized risk difference is 40 percentage points in both models.

Both models are correct; they estimate different odds ratios. The conditional odds ratio describes the treatment effect among participants with the same severity, whereas the marginal odds ratio describes the effect averaged over the whole trial. Standardizing the adjusted model recovers the marginal odds ratio, and the standardized risk difference does not depend on whether severity is in the model, because risk differences are collapsible.

7 Summary

  • An additive logistic model assumes a common treatment log-odds difference, not necessarily a constant probability difference.
  • An interaction model lets the treatment association vary with continuous baseline PHQ-9.
  • avg_comparisons(..., type = "response") supplies conditional and marginal treatment contrasts on the probability scale.
  • A contrast curve communicates both the estimated pattern and its uncertainty.
  • Odds ratios describe ratios of odds. They are not percentage-point changes in probability.
  • Odds ratios are non-collapsible: adjusting for a prognostic covariate changes the odds ratio even without confounding, whereas standardized risk differences keep their meaning.

References

Daniel, Rhian, Jingjing Zhang, and Daniel Farewell. 2021. “Making Apples from Oranges: Comparing Noncollapsible Effect Estimators and Their Standard Errors After Adjustment for Different Covariate Sets.” Biometrical Journal 63 (3): 528–57. https://doi.org/10.1002/bimj.201900297.
Greenland, Sander, Judea Pearl, and James M. Robins. 1999. “Confounding and Collapsibility in Causal Inference.” Statistical Science 14 (1): 29–46. https://doi.org/10.1214/ss/1009211805.
Hernán, Miguel A., and James M. Robins. 2020. Causal Inference: What If. Chapman & Hall/CRC.
Morris, Tim P., A. Sarah Walker, Elizabeth J. Williamson, and Ian R. White. 2022. “Planning a Method for Covariate Adjustment in Individually Randomised Trials: A Practical Guide.” Trials 23: 328. https://doi.org/10.1186/s13063-022-06097-z.
Robinson, Laurence D., and Nicholas P. Jewell. 1991. “Some Surprising Results about Covariate Adjustment in Logistic Regression Models.” International Statistical Review 59 (2): 227–40. https://doi.org/10.2307/1403444.
U.S. Food and Drug Administration. 2023. Adjusting for Covariates in Randomized Clinical Trials for Drugs and Biological Products: Guidance for Industry. Https://www.fda.gov/media/148910/download.