Logistic regression foundations

1 Why logistic regression?

Course 2 used linear and quantile regression to model continuous outcomes such as post-treatment LSAS scores. In many psychiatric research questions, the outcome is instead binary:

  • remission versus non-remission;
  • response versus non-response;
  • attendance versus dropout; or
  • an adverse event versus no adverse event.

Logistic regression and its multinomial extension are helpful tools when you want to analyze a binary or categorical outcome. This chapter uses a binary post-treatment social-anxiety outcome. Our main question is:

How does the probability of treatment response differ between treatment groups?

But first, some setup.

2 Packages and data

library(tidyverse)
library(here)
library(broom)
library(marginaleffects)
library(tinytable)

options(
  marginaleffects_print_omit = c("s.value"),
  marginaleffects_print_style = ifelse(interactive(), "summary", "tinytable")
)
df_clean <- 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")
    )
  )

df_clean |>
  count(lsas_response, .drop = FALSE)
lsas_response n
No response 112
Response 57

3 Defining the binary outcome

The binary outcome is treatment response:

lsas_response = "Response"    if LSAS decreases by at least 30%
lsas_response = "No response" otherwise

This follows the practical treatment-follow-up guidance for LSAS-SR, which describes improvement as an approximately 30% reduction in total score (Nationell formulärsamling). In a German treated-SAD sample, the empirically derived LSAS-SR response cut-point was 28% (Glischinski et al. 2018). We use the rounded 30% definition in this course.

CautionThe Cost of Dichotomizing

The 30% response definition is useful for this course, but it is not a diagnosis or a remission definition. Before creating a binary clinical outcome in your own work, specify the purpose and identify a defensible external definition.

Dichotomizing a continuous outcome also has a statistical cost. Participants just above and just below the 30% threshold are treated as completely different, while participants with 31% and 90% reductions are treated as identical. Splitting a normally distributed variable at its median loses about as much information as discarding a third of the sample (Altman and Royston 2006; MacCallum et al. 2002). The median is the most favorable split: a threshold that produces unequal groups, such as our 30% response definition, loses more (van Zwet et al. 2026).

Our outcome has two further problems. It is based on percentage change from baseline, which is a statistically inefficient outcome compared with post-treatment scores adjusted for baseline (Vickers 2001). And a responder split can make a uniform improvement look like a division into responders and non-responders: if every participant improved by the same number of points, some would still cross the threshold and others would not (Senn and Julious 2009).

The primary analysis of a continuous outcome such as LSAS should usually model the continuous score. A useful rule is to “model continuously but interpret dichotomously” (van Zwet et al. 2026): for example, report the percentage of participants with a clinically meaningful improvement as estimated from a model of the continuous score, rather than from dichotomized raw data. We dichotomize in this course to teach models for truly binary outcomes, not to recommend the practice.

4 The model behind logistic regression

Each participant either responds or does not. We write \(Y_i = 1\) for response and \(Y_i = 0\) otherwise, and treat \(Y_i\) as a Bernoulli variable, the single-trial case of the binomial distribution from Course 1:

\[ Y_i \sim \operatorname{Bernoulli}(p_i), \qquad p_i = P(Y_i = 1). \]

A Bernoulli variable has mean \(p_i\) and variance \(p_i(1 - p_i)\). A regression model for a binary outcome is therefore a model for the probability \(p_i\), and the variance follows from that probability rather than being estimated separately.

Logistic regression models a transformation of \(p_i\), the log-odds (defined in the next section), as a linear function of the predictors. Because the log-odds can take any real value, every value of the linear predictor corresponds to a probability between 0 and 1. glm(..., family = binomial) estimates the coefficients by maximum likelihood: it chooses the values that make the observed responses and non-responses most probable under the Bernoulli model. Unlike the linear models in Course 2, there is no residual variance \(\sigma^2\) to estimate.

4.1 Why not an ordinary linear model?

Nothing stops you from fitting lm() to a 0/1 outcome. This linear probability model has three problems as a general tool:

  • predictions can fall below 0 or above 1, particularly with numeric predictors;
  • the variance \(p_i(1 - p_i)\) changes with the predictors, so the usual standard errors are wrong unless robust standard errors are used; and
  • a straight line on the probability scale is rarely plausible close to 0 or 1.

With a single binary predictor such as treatment group, the linear probability model and logistic regression give the same two group probabilities, so the linear model’s slope equals the probability difference.

We use the logistic model throughout and obtain probability differences from it with marginaleffects.

5 Intercept-only logistic regression

We first ignore treatment group and estimate one probability: the probability that a participant has treatment response at post-treatment.

The model is:

\[ \operatorname{logit}\left[P(Y_i = \text{Response})\right] = \beta_0, \]

where the logit transforms a probability \(p\) into log-odds:

\[ \operatorname{logit}(p) = \log\left(\frac{p}{1-p}\right). \]

mod_intercept <- glm(
  lsas_response ~ 1,
  family = binomial,
  data = df_clean
)

summary(mod_intercept)

Call:
glm(formula = lsas_response ~ 1, family = binomial, data = df_clean)

Coefficients:
            Estimate Std. Error z value Pr(>|z|)    
(Intercept)  -0.6754     0.1627  -4.151  3.3e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 216.05  on 168  degrees of freedom
Residual deviance: 216.05  on 168  degrees of freedom
AIC: 218.05

Number of Fisher Scoring iterations: 4

The intercept is on the log-odds scale, so it is not the clearest clinical summary. If we exponentiate the estimate, we get it on the odds scale. This is the same as dividing the number of responders by the number of non-responders (see the counts above).

b_intercept <- coef(mod_intercept)[["(Intercept)"]]
exp(b_intercept) # odds of response from the model
[1] 0.5089286
# Odds by hand: number of responders divided by number of non-responders
n_outcome <- table(df_clean$lsas_response)
n_outcome[["Response"]] / n_outcome[["No response"]]
[1] 0.5089286

The odds is still not the clearest summary; the probability is usually easier to interpret. Convert the log-odds to a probability by hand using the inverse logit, \(p = e^x / (1 + e^x)\):

exp(b_intercept) / (1 + exp(b_intercept))
[1] 0.3372781

R’s plogis() applies the same inverse-logit transformation directly:

plogis(b_intercept)
[1] 0.3372781

We can use marginaleffects to obtain the estimated probability and its confidence interval. predictions() predicts the probability of response for the participants in newdata. An intercept-only model predicts the same probability for every participant, so we predict for one, the first row of the data.

p_overall <- predictions(mod_intercept, newdata = head(df_clean, 1))
p_overall
Estimate Pr(>|z|) 2.5 % 97.5 %
Type: invlink(link)
0.337 <0.001 0.27 0.412

The estimated probability of treatment response in the full analysis sample is 33.7% (95% CI 27.0% to 41.2%).

This is a model-based estimate of an overall probability, not a treatment effect. The intercept printed by summary() is the log-odds corresponding to this probability. The corresponding odds of response are exp(b_intercept) = 0.51.

6 Treatment as a binary predictor

To make a binary treatment comparison, we restrict the data to the waitlist and therapist-guided groups. Waitlist is the reference group.

df_binary <- df_clean |>
  filter(trt %in% c("waitlist", "therapist-guided")) |>
  droplevels()

df_binary |>
  count(trt, lsas_response, .drop = FALSE)
trt lsas_response n
waitlist No response 52
waitlist Response 6
therapist-guided No response 23
therapist-guided Response 31

The logistic model is:

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

mod_trt <- glm(
  lsas_response ~ trt,
  family = binomial,
  data = df_binary
)

summary(mod_trt)

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

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)    
(Intercept)          -2.1595     0.4311  -5.009 5.48e-07 ***
trttherapist-guided   2.4580     0.5115   4.806 1.54e-06 ***
---
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: 112.25  on 110  degrees of freedom
AIC: 116.25

Number of Fisher Scoring iterations: 4

The coefficient for therapist-guided is now the difference in the log-odds of response between the therapist-guided and waitlist groups. By exponentiating, we get the odds ratio. This can be calculated by hand from the counts above, by dividing the odds of response in the therapist-guided group by the odds in the waitlist group.

b_trt <- coef(mod_trt)[["trttherapist-guided"]]
exp(b_trt) # odds ratio from the model
[1] 11.68116
# Odds ratio by hand: odds of response by group, then their ratio
n_trt <- table(df_binary$trt, df_binary$lsas_response)
odds_by_trt <- n_trt[, "Response"] / n_trt[, "No response"]
odds_by_trt[["therapist-guided"]] / odds_by_trt[["waitlist"]]
[1] 11.68116

You can also use the convenient tidy() function from the broom package to get the odds ratio and its confidence interval.

or_trt <- tidy(mod_trt, conf.int = TRUE, exponentiate = TRUE)
or_trt_contrast <- or_trt |>
  filter(term == "trttherapist-guided")

6.1 Estimated probabilities, a probability difference, and a probability ratio (a.k.a. risk ratio)

datagrid(trt = unique) makes one row per treatment group, so predictions() returns the probability of response for a participant in each group.

p_by_trt <- predictions(mod_trt, newdata = datagrid(trt = unique))
p_by_trt
trt Estimate Pr(>|z|) 2.5 % 97.5 %
Type: invlink(link)
waitlist 0.103 <0.001 0.0472 0.212
therapist-guided 0.574 0.278 0.4401 0.698
trt_difference <- avg_comparisons(
  mod_trt,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "response"
)
trt_difference
Estimate Std. Error z Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: therapist-guided - waitlist
Type: response
0.471 0.0783 6.01 <0.001 0.317 0.624
trt_ratio <- avg_comparisons(
  mod_trt,
  variables = list(trt = c("waitlist", "therapist-guided")),
  type = "response",
  comparison = "lnratioavg",
  transform = exp
)
trt_ratio
Estimate Pr(>|z|) 2.5 % 97.5 %
Term: trt
Comparison: ln(mean(therapist-guided) / mean(waitlist))
Type: response
5.55 <0.001 2.51 12.2

Compared with waitlist, therapist-guided treatment changes the estimated probability of treatment response by 47.1 percentage points (95% CI 31.7 to 62.4 percentage points).

The estimated probability of treatment response is 5.55 times as high in the therapist-guided group as in the waitlist group (probability ratio/risk ratio; 95% CI 2.51 to 12.25).

This is an unadjusted treatment contrast in the restricted waitlist-versus-therapist-guided sample. A positive value means that therapist-guided treatment has a higher estimated probability of treatment response.

The therapist-guided-versus-waitlist odds ratio is 11.68 (95% CI 4.54 to 34.62).

NoteWhere does this risk ratio come from?

marginaleffects does not convert the odds ratio into a risk ratio. It predicts every participant’s probability of response under waitlist and under therapist-guided treatment, averages each set of predictions, and divides the two averages. Predicting every participant under both treatments means the two averages describe the same people, so they differ only in treatment. In this unadjusted model each scenario simply reproduces the group’s observed proportion. This approach is called marginal standardization (Localio et al. 2007), also known as G-computation (Morris et al. 2022). The result is a marginal (population-averaged) risk ratio: it averages over the participants in the sample, rather than describing a conditional risk ratio at particular covariate values. The comparison argument lnratioavg means, read from right to left: avg averages the predicted probabilities in each scenario, ratio divides the therapist-guided average by the waitlist average, and ln takes the natural log of that ratio. transform = exp then exponentiates the estimate and its confidence limits, returning them to the ratio scale. The detour through the log scale is for the confidence interval. This is the same device predictions() used for the group probabilities above, with the log in place of the log-odds. A ratio cannot fall below 0, and its sampling distribution is skewed, particularly when one group has few events, as the waitlist group does here. On the log scale the distribution is closer to symmetric, so the normal-approximation interval that marginaleffects builds from its delta-method standard error works better, and exponentiating its limits gives an interval that is asymmetric around the estimate and stays above 0. This log risk ratio is not the log-odds that the logistic model estimates; it is computed from the predicted probabilities.

Show the same calculation by hand
# Counterfactual datasets: everyone on waitlist, everyone therapist-guided
df_waitlist <- mutate(
  df_binary,
  trt = factor("waitlist", levels = levels(trt))
)
df_guided <- mutate(
  df_binary,
  trt = factor("therapist-guided", levels = levels(trt))
)
x_waitlist <- model.matrix(~trt, df_waitlist)
x_guided <- model.matrix(~trt, df_guided)

# ln(ratio of average predicted probabilities), as a function of the
# coefficients
log_rr <- function(beta) {
  log(mean(plogis(x_guided %*% beta)) / mean(plogis(x_waitlist %*% beta)))
}
beta_hat <- coef(mod_trt)

# Delta method: numerical gradient of log_rr, then the standard error on
# the log scale
h <- 1e-6
gradient <- map_dbl(seq_along(beta_hat), \(j) {
  step <- replace(numeric(length(beta_hat)), j, h)
  (log_rr(beta_hat + step) - log_rr(beta_hat)) / h
})
se_log_rr <- sqrt(drop(t(gradient) %*% vcov(mod_trt) %*% gradient))

# 95% interval on the log scale, then exponentiate (transform = exp)
z <- qnorm(0.975)
exp(
  log_rr(beta_hat) + c(estimate = 0, conf.low = -z, conf.high = z) * se_log_rr
)
 estimate  conf.low conf.high 
 5.549383  2.514382 12.247802 

Shortcut formulas that convert a published odds ratio into a risk ratio using the baseline risk are a different thing: they are biased for adjusted odds ratios and give incorrect confidence intervals (McNutt et al. 2003).

Another well-established way to estimate a risk ratio from a binary outcome is Poisson regression with robust (sandwich) standard errors (Zou 2004). In this unadjusted two-group model, both routes give the same risk ratio, 5.55. They can differ in adjusted models: Poisson regression assumes one risk ratio for every covariate pattern and can predict probabilities above 1, whereas standardization from a logistic model averages over the covariate distribution of the sample.

6.2 Visualize the estimated probabilities

plot_predictions(mod_trt, condition = "trt") +
  labs(
    title = "Estimated probability of treatment response",
    subtitle = "Binary logistic regression; 95% confidence intervals",
    x = "Treatment group",
    y = "Probability of treatment response"
  ) +
  theme_minimal()

7 Odds, log-odds, and odds ratios

The coefficient for trttherapist-guided in summary(mod_trt) is a log-odds difference. Exponentiating it yields an odds ratio.

or_trt
term estimate std.error statistic p.value conf.low conf.high
(Intercept) 0.1153846 0.4311336 -5.008852 5.0e-07 0.0443435 0.2477784
trttherapist-guided 11.6811593 0.5114807 4.805611 1.5e-06 4.5423729 34.6221036

An odds ratio above 1 indicates higher odds of the modeled event (Response) in therapist-guided treatment than waitlist. It does not mean that the probability is that many times larger, and it does not tell us the percentage-point difference.

7.1 Odds ratios and risk ratios when the outcome is common

When an outcome is rare, odds and probabilities are almost equal, so the odds ratio approximates the probability ratio (risk ratio). Treatment response is not rare here: the estimated probability of response in the therapist-guided group is 57%. The therapist-guided-versus-waitlist odds ratio is 11.7, whereas the probability ratio from the previous section is 5.5. Read as a risk ratio, the odds ratio would overstate the relative effect by a factor of 2.1. When the odds ratio is above 1, it is always further from 1 than the risk ratio, and the gap widens as the outcome becomes more common (Davies et al. 1998).

NoteReading an odds ratio in a paper

Suppose an article reports an odds ratio of 2. The odds are doubled, but the probability is not: it always rises by less than a factor of 2, and comes close to doubling only when the outcome is rare. With a baseline probability of 10%, doubling the odds raises the probability to 18%; with a baseline probability of 50%, it raises it to 67%. The same odds ratio thus corresponds to a 8-percentage-point increase in one setting and a 17-percentage-point increase in the other. This is why we pair odds ratios with estimated probabilities and probability differences when communicating clinical results.

8 Summary

In this chapter you learned to:

  • define a binary LSAS outcome and distinguish it from a validated clinical threshold;
  • describe a binary outcome as a Bernoulli variable and explain why logistic regression is preferred to a linear probability model;
  • explain why an odds ratio overstates the risk ratio when the outcome is common;
  • fit intercept-only and treatment logistic regression models with glm(..., family = binomial);
  • interpret model output through estimated probabilities and probability differences with 95% CIs;
  • visualize treatment-group probabilities with marginaleffects; and
  • recognize an odds ratio as a ratio of odds rather than a probability difference.

References

Altman, Douglas G., and Patrick Royston. 2006. “The Cost of Dichotomising Continuous Variables.” BMJ 332 (7549): 1080. https://doi.org/10.1136/bmj.332.7549.1080.
Davies, Huw Talfryn Oakley, Iain Kinloch Crombie, and Manouche Tavakoli. 1998. “When Can Odds Ratios Mislead?” BMJ 316 (7136): 989–91. https://doi.org/10.1136/bmj.316.7136.989.
Glischinski, M. von, U. Willutzki, U. Stangier, et al. 2018. “Liebowitz Social Anxiety Scale (LSAS): Optimal Cut Points for Remission and Response in a German Sample.” Clinical Psychology & Psychotherapy 25 (3): 465–73. https://doi.org/10.1002/cpp.2179.
Localio, A. Russell, David J. Margolis, and Jesse A. Berlin. 2007. “Relative Risks and Confidence Intervals Were Easily Computed Indirectly from Multivariable Logistic Regression.” Journal of Clinical Epidemiology 60 (9): 874–82. https://doi.org/10.1016/j.jclinepi.2006.12.001.
MacCallum, Robert C., Shaobo Zhang, Kristopher J. Preacher, and Derek D. Rucker. 2002. “On the Practice of Dichotomization of Quantitative Variables.” Psychological Methods 7 (1): 19–40. https://doi.org/10.1037/1082-989X.7.1.19.
McNutt, Louise-Anne, Chuntao Wu, Xiaonan Xue, and Jean Paul Hafner. 2003. “Estimating the Relative Risk in Cohort Studies and Clinical Trials of Common Outcomes.” American Journal of Epidemiology 157 (10): 940–43. https://doi.org/10.1093/aje/kwg074.
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.
Senn, Stephen, and Steven Julious. 2009. “Measurement in Clinical Trials: A Neglected Issue for Statisticians?” Statistics in Medicine 28 (26): 3189–209. https://doi.org/10.1002/sim.3603.
Vickers, Andrew J. 2001. “The Use of Percentage Change from Baseline as an Outcome in a Controlled Trial Is Statistically Inefficient: A Simulation Study.” BMC Medical Research Methodology 1: 6. https://doi.org/10.1186/1471-2288-1-6.
Zou, Guangyong. 2004. “A Modified Poisson Regression Approach to Prospective Studies with Binary Data.” American Journal of Epidemiology 159 (7): 702–6. https://doi.org/10.1093/aje/kwh090.
Zwet, Erik W. van, Frank E. Harrell Jr, and Stephen J. Senn. 2026. “An Empirical Assessment of the Cost of Dichotomization of the Outcome of Clinical Trials.” Statistics in Medicine 45 (3–5): e70402. https://doi.org/10.1002/sim.70402.