Logistic Regression
with glm() in R
Learn to fit and interpret binary classification models using R's glm() function with family = binomial.
What Is Logistic Regression?
Logistic regression is a classification algorithm that predicts the probability of a binary outcome (yes/no, pass/fail, 0/1). Unlike linear regression, which outputs any real number, logistic regression outputs a probability between 0 and 1.
The Sigmoid Function
The sigmoid (logistic) function transforms any real-valued input into a probability:
Why Not Linear Regression?
When the outcome is binary, a straight line is a poor model. It can predict values below 0 or above 1, which don't make sense as probabilities.
The Logit Link Function
Logistic regression models the log-odds of the outcome as a linear function of predictors. The logit function is the inverse of the sigmoid:
R's glm() Function
In R, glm() stands for Generalized Linear Model. To fit a logistic regression, you set family = binomial:
lm() vs glm()
| lm() | glm(..., binomial) | |
|---|---|---|
| Outcome Type | Continuous | Binary (0/1) |
| Output Range | \( (-\infty, +\infty) \) | \( [0, 1] \) |
| Link Function | Identity | Logit |
| Loss Function | Least Squares | Max Likelihood |
| Coefficients Mean | Change in \( Y \) | Change in log-odds |
| Fit Measure | \( R^2 \) | AIC, Deviance |
Step-by-Step Workflow
Example: Fitting the Model
Predict whether a student passes an exam (1 = pass, 0 = fail) based on hours studied:
Reading summary() Output
Interpreting Coefficients
Coefficients in logistic regression are on the log-odds scale. To get odds ratios, exponentiate them:
Making Predictions
Adding Multiple Predictors
Just like lm(), you can include multiple predictors and even interaction terms:
The Full Pipeline
Common Mistakes
Quick Reference Cheat Sheet
| Task | R Code |
|---|---|
| Fit model | glm(y ~ x, data, family = binomial) |
| View results | summary(model) |
| Odds ratios | exp(coef(model)) |
| CI for odds ratios | exp(confint(model)) |
| Predict probabilities | predict(model, newdata, type = "response") |
| Model fit | AIC(model) or model$deviance |
Question 1 of 5
Which argument in glm() tells R to perform logistic regression instead of linear regression?
Question 2 of 5
If a logistic regression coefficient for hours is \( \beta = 0.8 \), what is the odds ratio?
Question 3 of 5
What does predict(model, newdata) return by default (without specifying type) for a logistic regression model?
Question 4 of 5
The logistic regression equation is \( \text{logit}(p) = -3 + 2x \). What is the predicted probability when \( x = 1 \)?
Question 5 of 5
Which R function do you use to obtain confidence intervals for odds ratios from a logistic regression model?