Logistic Regression in R
A probability model needs a link, not a line
Fitting a straight line to a zero-or-one response produces nonsense: fitted values below zero or above one, residuals that are never normally distributed, and heteroscedasticity that grows toward the middle of the range. Logistic regression solves this by modelling the log-odds of success as a linear function of the predictors, which maps the whole real line onto the interval from zero to one and makes the error structure match a binary outcome.
The price of that fix is interpretation. A coefficient no longer means "change in probability per unit"; it means "change in log-odds per unit", and converting back to probabilities requires knowing where you started. Every section below is about making that conversion explicit rather than leaving readers to guess.
- Fit the model with glm() and the binomial family.
- Exponentiate coefficients into odds ratios with intervals.
- Separate the model's ranking ability from the threshold you choose to act on.
Prerequisites
- !Linear regression and coefficient interpretation
- !Probability, odds, and the logit transformation
What You'll Learn
- 1Fit binary logistic regression and read the coefficient table correctly
- 2Convert log-odds into odds ratios and predicted probabilities
- 3Evaluate models with confusion matrices, ROC curves, and AUC
- 4Extend to multinomial and ordinal outcomes when categories are more than two
Fitting and reading the coefficient table
The formula syntax is identical to linear regression; only the family argument changes. R reports coefficients on the log-odds scale, so the raw estimate is rarely the number you want to quote â but its sign and its significance are directly interpretable as evidence about direction.
churn_data <- read.csv("data/customers.csv", stringsAsFactors = FALSE)
churn_data$churn <- factor(churn_data$churn, levels = c("No", "Yes"))
model <- glm(churn ~ tenure + monthly_charges + contract,
data = churn_data, family = binomial)
summary(model)
# On the log-odds scale
coef(model)
confint(model, level = 0.95)
# Odds ratios with intervals: the reportable numbers
exp(cbind(Odds = coef(model), confint(model)))
# Predicted probabilities for the training data
churn_data$p <- predict(model, type = "response")
# New customer
new_cust <- data.frame(tenure = 4, monthly_charges = 89.5,
contract = "Month-to-month")
predict(model, newdata = new_cust, type = "response")
type = "response" is the switch that matters. Without it, predict() returns log-odds, and a common bug is comparing those values to 0.5 as though they were probabilities. Significance in the table is a Wald test on the log-odds coefficient, which behaves like a t-test in linear regression but degrades when a predictor almost perfectly separates the classes â a situation covered in the diagnostics section.
It is also worth pausing on what the model assumes. The logit link forces the relationship between each predictor and the outcome to be a smooth S-curve, symmetric around the fifty-fifty point, which means a continuous predictor's influence is strongest where the fitted probability sits near the middle and weakens toward both ends. That is usually the right shape for real events â tenure matters most for customers who are already marginal â but it is an assumption, and a predictor whose true effect saturates early or late will be misrepresented by a single linear term in log-odds. Checking the fitted probability against the raw predictor with a binned plot is the quickest way to see whether the S-curve matches reality.
| Scale | Value for a coefficient | How to read it |
|---|---|---|
| Log-odds | 0.72 | log of the odds multiplier per unit |
| Odds ratio | 2.05 | odds multiply by 2.05 per unit |
| Probability | context-dependent | depends on the starting probability |
| Odds | 1 to 1 | odds of success before any predictor acts |
Odds ratios in plain language
An odds ratio above one raises the odds of the event; below one lowers them. The subtlety is that odds and probability diverge as the base rate moves away from 0.5, so the same odds ratio implies a large probability change for a rare event and a small one for a common event. Concretely: if a customer's baseline churn probability is 0.10, an odds ratio of 2.0 moves them to roughly 0.18; from a baseline of 0.50, the same multiplier moves them to about 0.67.
# Probability implied by an odds ratio at a given baseline
prob_after <- function(p0, or) {
odds0 <- p0 / (1 - p0)
odds1 <- odds0 * or
odds1 / (1 + odds1)
}
prob_after(0.10, 2.0) # rare event: large relative move
prob_after(0.50, 2.0) # common event: smaller move
prob_after(0.50, 0.5) # protective factor halves the odds
# Continuous predictor: effect over a realistic range
b <- coef(model)
p_low <- plogis(b[1] + b[2] * 1)
p_high <- plogis(b[1] + b[2] * 60)
p_high - p_low
# Categorical contrasts against the reference level
library(emmeans)
emmeans(model, ~ contract, type = "response")
Reporting the probability shift over a realistic range is almost always clearer than quoting an odds ratio, because readers reason in chances rather than in odds. For continuous predictors, evaluate the fitted probability at the tenth and ninetieth percentile of the variable rather than for a one-unit change, since a single unit of tenure or revenue may be too small to notice.
From probabilities to decisions
A model outputs probabilities; a business action is binary. The mapping between them is a threshold, and the best threshold is a cost decision rather than a statistical one. Setting it at 0.5 implicitly says a false positive and a false negative cost the same, which is rarely true: missing a fraudulent transaction and flagging a legitimate one are not symmetric.
library(pROC)
churn_data$pred_class <- ifelse(churn_data$p > 0.5, "Yes", "No")
# Confusion matrix and its summary
table(Predicted = churn_data$pred_class, Actual = churn_data$churn)
caret::confusionMatrix(factor(churn_data$pred_class), churn_data$churn)
# Threshold sweep driven by costs
cost_fp <- 5 # contacting a happy customer
cost_fn <- 200 # losing a churner
thresholds <- seq(0.05, 0.95, by = 0.05)
cost_curve <- sapply(thresholds, function(t) {
pred <- factor(ifelse(churn_data$p > t, "Yes", "No"),
levels = c("No", "Yes"))
cm <- table(Predicted = pred, Actual = churn_data$churn)
fp <- cm["Yes", "No"]
fn <- cm["No", "Yes"]
fp * cost_fp + fn * cost_fn
})
best <- thresholds[which.min(cost_curve)]
plot(thresholds, cost_curve, type = "b",
xlab = "Threshold", ylab = "Total cost")
abline(v = best, lty = 2)
The cost curve usually has a flat bottom, which is good news: the exact threshold matters less than moving off 0.5 in the right direction. Present the curve, not just the optimum, so stakeholders see how sensitive the decision is.
Discrimination and calibration
AUC measures how often the model ranks a randomly chosen positive above a randomly chosen negative, so it evaluates ordering and ignores thresholds entirely. Calibration asks a different question: among customers the model assigns 0.30, does roughly 30 per cent actually churn? A model can be excellent at one and poor at the other, and production systems usually need both.
library(pROC)
roc_obj <- roc(churn_data$churn, churn_data$p)
auc(roc_obj)
plot(roc_obj, legacy.axes = TRUE,
xlab = "False positive rate", ylab = "True positive rate")
coords(roc_obj, "best", ret = c("threshold", "sensitivity", "specificity"))
# Calibration check in deciles
churn_data$decile <- cut(churn_data$p, breaks = quantile(churn_data$p,
probs = seq(0, 1, by = 0.1)), include.lowest = TRUE)
calibration <- aggregate(cbind(p, observed = as.integer(churn_data$churn == "Yes")) ~ decile,
data = churn_data, FUN = mean)
calibration$gap <- calibration$p - calibration$observed
calibration
# Brier score: overall probability accuracy
mean((churn_data$p - as.integer(churn_data$churn == "Yes"))^2)
Imbalanced classes are where accuracy misleads most. If only four per cent of customers churn, a model that predicts "No" for everyone scores 96 per cent accuracy and has an AUC of 0.5. Precision, recall, and AUC are the metrics that expose this, and the precision-recall curve is the more informative companion to ROC when positives are rare.
When the outcome has more than two categories
Two extensions cover the common cases. Multinomial logistic regression handles unordered categories such as plan tiers and fits one log-odds equation per non-reference level. Ordinal logistic regression handles ordered categories such as satisfaction bands and fits a single set of coefficients with cut-points, which imposes the proportional-odds assumption worth testing.
# Unordered categories: one baseline, one set of coefficients per level
library(nnet)
plans <- multinom(plan ~ tenure + channel + spend, data = subscribers)
summary(plans)
exp(coef(plans))
table(Predicted = predict(plans), Actual = subscribers$plan)
# Ordered categories: proportional odds
library(MASS)
satisfaction <- factor(subscribers$satisfaction,
levels = c("Low", "Medium", "High"),
ordered = TRUE)
ordinal_fit <- polr(satisfaction ~ tenure + support_tickets, data = subscribers,
Hess = TRUE)
exp(coef(ordinal_fit))
# Test proportional odds; a small p-value means the assumption fails
library(lmtest)
lrtest(ordinal_fit)
# If it fails, fall back to a multinomial fit for the same predictors
multinom(satisfaction ~ tenure + support_tickets, data = subscribers)
Proportional odds assumes the same coefficients explain every cut-point in the ordered outcome. When that fails â often because a predictor matters at the low-to-medium boundary but not at medium-to-high â the multinomial model gives up efficiency but remains correct, and comparing the two is the standard diagnostic.
Diagnostics, separation, and influence
Logistic models fail differently from linear ones. Complete separation occurs when a predictor perfectly predicts the outcome, producing coefficients that diverge toward infinity with vanishing standard errors and warnings from R. Quasi-separation is milder and shows up as a single enormous coefficient with a huge interval.
model <- glm(churn ~ tenure + monthly_charges + contract,
data = churn_data, family = binomial)
# Separation check: any coefficient exploding toward infinity?
max(abs(coef(model)))
any(is.na(coef(model))) # failed to converge
model$converged
# Goodness of fit against the intercept-only model
with(model, pchisq(null.deviance - deviance,
df.null - df.residual, lower.tail = FALSE))
# Hosmer-Lemeshow style calibration test in deciles
library(ResourceSelection)
hoslem.test(as.integer(churn_data$churn == "Yes"), churn_data$p, g = 10)
# Influential observations
cd <- cooks.distance(model)
which(cd > 4 / nrow(churn_data))
# Residual types for inspection
res <- residuals(model, type = "deviance")
plot(fitted(model), res, pch = 16, cex = 0.6,
xlab = "Fitted probability", ylab = "Deviance residual")
abline(h = 0, lty = 2)
# Class imbalance: reweight rather than resample
weighted <- glm(churn ~ tenure + monthly_charges + contract,
data = churn_data, family = binomial,
weights = ifelse(churn_data$churn == "Yes", 3, 1))
When separation appears, the remedy is substantive: drop the separating predictor, combine sparse categories, or switch to a penalised fit such as Firth's, which keeps coefficients finite. Ignoring the warning yields a model that looks precise and is not. Deviance residuals plotted against fitted values serve the same role as residual plots in linear regression â bands or funnels indicate missing terms or variance problems.
Mistakes that make probabilities untrustworthy
Common Mistakes
Comparing predict() output to 0.5 without type = 'response'
Fix: Pass type = 'response' explicitly; the default returns log-odds and will misclassify nearly every row.
Quoting an odds ratio as a probability change
Fix: Convert through the baseline probability, or report the fitted probability at realistic predictor values.
Accepting accuracy on an imbalanced dataset
Fix: Report precision, recall, AUC, and the precision-recall curve alongside accuracy.
Choosing 0.5 as the threshold without a cost model
Fix: Sweep thresholds against explicit false-positive and false-negative costs and show the curve.
Ignoring convergence warnings from glm()
Fix: Inspect coefficients for divergence; separation or near-separation needs a different specification or penalised fit.
Evaluating the model on the same rows used to fit it
Fix: Hold out a test set or use cross-validation for every performance number you report.
Applying ordinary logistic regression to ordered categories
Fix: Use polr() for ordinal outcomes and test proportional odds before trusting the single coefficient set.
Practices that keep logistic models honest
Best Practices
- Report odds ratios with confidence intervals and a probability translation for a realistic case.
- Separate model evaluation (AUC, calibration) from threshold selection (cost, capacity).
- Check calibration deciles whenever the outputs feed a risk score or a financial forecast.
- Inspect coefficient magnitudes for separation before believing any significance test.
- Use class weights or stratified sampling rather than naive accuracy on rare events.
- Reserve a test set and never tune the threshold on it.
- Document the reference level of every categorical predictor so coefficient signs are interpretable.
Key takeaways
Key Takeaways
- Logistic regression models log-odds linearly so fitted probabilities stay inside zero and one.
- Exponentiating a coefficient gives the odds multiplier per unit; convert through a baseline to get probabilities.
- The 0.5 threshold is a cost assumption, not a statistical default â choose it with an explicit cost curve.
- AUC measures ranking quality and says nothing about calibration; production models usually need both.
- On imbalanced data, accuracy is nearly meaningless while precision, recall, and AUC remain informative.
- Multinomial models handle unordered categories and polr() handles ordered ones, subject to proportional odds.
- Separation, convergence warnings, and huge standard errors are the logistic equivalents of a broken fit.
Where to go next
- R Linear Regression â the estimation ideas logistic regression extends.
- R Time Series Analysis â modelling outcomes that arrive in sequence.
- R Machine Learning with caret â cross-validated evaluation across many classifiers.