library(ggplot2) # Visualization
library(MASS) # Dose at a given probability with dose.p()
library(effects) # Fitted effects and confidence bands
theme_set(theme_light())8. Generalized linear models in R
Linear models assume a normally distributed response with constant variance. Many ecological responses break these assumptions, such as proportions, presence/absence data or counts. Generalized linear models (GLMs) handle such data by combining a suitable response distribution with a link function. In this lab, we fit GLMs with glm(), starting from the linear model and moving on to logistic regression for proportion and binary data.
Packages
Recap: the linear model
GLMs build on the linear model, so we first write it in a form that we can extend. In the linear model, the response \(y_i\) is modeled by a linear function of explanatory variables \(x_{ik}\) plus a residual term \(\epsilon_i\),
\[ y_i = \beta_{0} + \beta_{1} x_{i1} + ... + \beta_{k} x_{ik} + \epsilon_i \]
where \(i\) is the observation index and \(k\) is the index of explanatory variables. Because the residuals have mean zero, the linear function describes the mean response:
\[ E[y_i] = \beta_{0} + \beta_{1} x_{i1} + ... + \beta_{k} x_{ik} \]
We assume that the residuals \(\epsilon_i\) are independent and identically normally distributed with mean 0 and variance \(\sigma^2\):
\[ \epsilon_i \sim N(0, \sigma^2) \]
This can also be written in terms of \(y_i\), with the linear predictor as the mean response and variance \(\sigma^2\) (standard deviation \(\sigma\)).
\[ y_i \sim N(E[y_i], \sigma^2) \]
What is a GLM?
A GLM extends the linear model with three components:
- Response distribution: the distribution of \(y_i\), e.g. normal, binomial or Poisson. It also sets how the variance relates to the mean.
- Linear predictor: the linear function of the explanatory variables, \(\eta_i = \beta_0 + \beta_1 x_{i1} + \dots + \beta_k x_{ik}\).
- Link function: \(g(E[y_i]) = \eta_i\) connects the mean response to the linear predictor.
The linear model is the special case with a normal distribution and the identity link, \(E[y_i] = \eta_i\).
Fitting GLMs in R
GLMs are fitted in R with the glm() function, which works like lm(). Its main arguments are (see ?glm for the full list):
glm(formula, family = gaussian, data, weights, subset, ...)Family argument
The family argument takes a family function (or its name), which specifies
- the response distribution
- the link function
The exponential family functions available in R are
binomial(link = "logit")gaussian(link = "identity")Gamma(link = "inverse")inverse.gaussian(link = "1/mu^2")poisson(link = "log")
The links shown are the defaults. Other links can be chosen if there is reason to do so.
Extractor functions
glm() returns an object of class c("glm", "lm"). Its components can be accessed with the same functions as for lm objects, including:
residuals()fitted()predict()coef()deviance()formula()summary()
From LM to GLM: link functions
Recall the regression of ozone on temperature and wind from the airquality data:
\[E[y_i] = \beta_{0} + \beta_{1} \text{Temp}_i + \beta_2 \text{Wind}_i + \beta_3 \text{Temp}_i \text{Wind}_i\]
The residuals were poorly distributed because ozone concentrations are bounded to positive values. We therefore log-transformed the response:
\[E[\log(y_i)] = \beta_{0} + \beta_{1} \text{Temp}_i + \beta_2 \text{Wind}_i + \beta_3 \text{Temp}_i \text{Wind}_i\]
However, a transformed response makes the model harder to interpret, and back-transforming standard errors and confidence intervals is difficult. GLMs instead transform the mean response with the link function \(g()\), not the individual \(y_i\)’s. Compare with the equation above:
\[g(E[y_i]) = \beta_{0} + \beta_{1} \text{Temp}_i + \beta_2 \text{Wind}_i + \beta_3 \text{Temp}_i \text{Wind}_i = \eta_i\]
The inverse-link function \(g^{-1}()\) back-transforms the linear predictor to the mean response:
\[E[y_i] = g^{-1}(\eta_i)\]
With the identity link and a normal distribution, this is the linear model, so glm() and lm() give identical results:
fit_lm <- lm(Ozone ~ Temp * Wind, data = na.omit(airquality))
coef(fit_lm)(Intercept) Temp Wind Temp:Wind
-239.891827 4.000528 13.597458 -0.217276
fit_glm <- glm(Ozone ~ Temp * Wind, data = na.omit(airquality), family = gaussian(link = "identity"))
coef(fit_glm)(Intercept) Temp Wind Temp:Wind
-239.891827 4.000528 13.597458 -0.217276
To account for the non-linear relationship, we now use a log link, \(g(E[y_i]) = \log(E[y_i])\), instead of log-transforming \(y_i\). For a simpler plot, we use temperature as the only predictor:
fit_glm <- glm(Ozone ~ Temp, data = na.omit(airquality), family = gaussian(link = "log"))The inverse link is \(E[y_i] = e^{\eta_i}\). The distribution is still normal, so the model is
\[y_i \sim N(e^{\eta_i}, \sigma^2)\]
whereas the linear model with log-transformed response is
\[y_i \sim e^{N(\eta_i, \sigma^2)}\]
The two models are not identical. Most noticeable are the confidence bands of the linear model, which are narrow at low and very wide at high temperatures. They are symmetric on the log scale, so they widen with the fitted value when back-transformed. The back-transformed line also estimates the median rather than the mean ozone concentration.

Despite these differences, the GLM is not the better model here. The log link only changes how the mean depends on temperature. The normal distribution still assumes the same variance at all fitted values, but the spread of ozone increases with its mean. The log-transformed linear model has multiplicative errors, so its spread grows with the mean, and it fits the data better. Link function and response distribution are thus two separate choices.
A wrong variance assumption is easy to miss, because the fitted line can still look fine. In the chapter on Simulating GLMs, we introduce simulations to detect such problems. Ozone values simulated from the GLM with a log link scatter too widely at low and too narrowly at high temperatures, whereas values from the log-transformed linear model follow the observed scatter much more closely.
- Fitted values and confidence intervals are on the original scale of the response, not on a transformed scale.
- The link function can be chosen to match the range of the response, e.g. positive values or values between 0 and 1.
- The response distribution can be chosen to match the type of data, e.g. counts, proportions or binary outcomes.
Logistic regression
Logistic regression models the probability \(p\) of an event, such as death, infestation or presence, as a function of predictors. The data can come in two forms:
- Proportion data: for each observation we know the number of events \(k\) out of \(n\) trials, e.g. the number of dead individuals out of those exposed to a toxic substance. The response follows a binomial distribution, \(k \sim \text{Binomial}(n, p)\).
- Binary data: each observation is a single trial with outcome 0 or 1, e.g. whether a tree is infested by bark beetles or not. The response follows a Bernoulli distribution, which is a binomial distribution with \(n = 1\).
Both cases are the same model: a binomial response whose probability \(p\) is linked to the predictors through the logit link. They differ only in the number of trials per observation. In R, both use family = binomial, but the response is specified differently: a 0/1 variable for binary data, and cbind(events, non-events) for proportion data. Using the counts rather than the proportion \(k/n\) alone matters, because a proportion based on 20 trials carries more information than one based on 2 trials.
Proportion data
In a toxicity experiment, groups of individuals were exposed to three toxic substances (product) at different doses (logdose, on the log scale). For each group, the data record the number of exposed individuals (n) and the number that died (dead):
dat <- read.table("data/logistic.txt", sep = "\t", header = TRUE)
head(dat) logdose n dead product
1 0.1 18 0 A
2 0.2 16 4 A
3 0.3 21 7 A
4 0.4 19 6 A
5 0.5 16 5 A
6 0.6 20 10 A
Plotting the proportion of dead individuals (dead / n) against the dose shows how mortality changes with dose for each substance:
ggplot(dat, aes(x = logdose, y = dead / n, col = product)) +
geom_point()
For all three substances, mortality rises with dose, from 0–0.25 at the lowest dose to 0.8–1.0 at high doses. Product B is the exception at high doses: its mortality levels off at about 0.6–0.7 above a log dose of 1.1.
We model mortality, which is bounded between 0 and 1, as a function of dose. We assume a binomial distribution (dead events out of n trials) and use the logit link, whose inverse is bounded between 0 and 1. The response combines the dead and surviving individuals with cbind():
fit1 <- glm(cbind(dead, n - dead) ~ logdose,
data = dat,
family = binomial(link = "logit"))
summary(fit1)
Call:
glm(formula = cbind(dead, n - dead) ~ logdose, family = binomial(link = "logit"),
data = dat)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.5980 0.1555 -10.27 <2e-16 ***
logdose 2.3179 0.1699 13.64 <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: 311.241 on 50 degrees of freedom
Residual deviance: 72.387 on 49 degrees of freedom
AIC: 223.39
Number of Fisher Scoring iterations: 4
The coefficients are on the link (log-odds) scale. We learn how to interpret them further below. The effect of logdose is significant (p < 0.001), and adding it reduces the deviance from 311 (null deviance, intercept only) to 72 (residual deviance). Unlike lm(), the output of glm() does not include an \(R^2\). Instead, we can compute a pseudo-\(R^2\) from the two deviances, which measures the goodness of fit similar to the \(R^2\) of a linear regression:
pseudo_r2 <- 1 - fit1$deviance / fit1$null.deviance
pseudo_r2[1] 0.7674258
We add the fitted line to the scatter plot:
dat$fitted1 <- predict(fit1, type = "response") # type = "link" would return log-odds
ggplot(dat, aes(x = logdose, y = dead/n)) +
geom_point() +
geom_line(data = dat, aes(x = logdose, y = fitted1)) 
The model fits a single dose-response curve to all three substances, although the scatter plot suggests that product B behaves differently. To allow each substance its own curve, we add product and its interaction with logdose. The product term shifts the curve up or down for each substance. The interaction lets the slope differ between substances:
fit2 <- glm(cbind(dead, n - dead) ~ logdose * product,
data = dat,
family = binomial(link = "logit"))
summary(fit2)
Call:
glm(formula = cbind(dead, n - dead) ~ logdose * product, family = binomial(link = "logit"),
data = dat)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.0410 0.3034 -6.728 1.72e-11 ***
logdose 2.8768 0.3432 8.383 < 2e-16 ***
productB 1.2920 0.3845 3.360 0.00078 ***
productC -0.3079 0.4308 -0.715 0.47469
logdose:productB -1.6457 0.4220 -3.899 9.65e-05 ***
logdose:productC 0.4318 0.4898 0.882 0.37793
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 311.241 on 50 degrees of freedom
Residual deviance: 42.305 on 45 degrees of freedom
AIC: 201.31
Number of Fisher Scoring iterations: 4
Separate curves for each substance increase the pseudo-\(R^2\) compared to fit1:
pseudo_r2 <- 1 - fit2$deviance / fit2$null.deviance
pseudo_r2[1] 0.8640758
The residual deviance also tells us whether the binomial distribution fits the variation in the data. If it does, the residual deviance is close to its degrees of freedom. For fit1, it is clearly larger (72 on 49 degrees of freedom), which indicates more variation than the binomial distribution expects (overdispersion). For fit2, the ratio is close to 1 (42 on 45 degrees of freedom), so the extra variation in fit1 came from ignoring the differences between substances. We return to overdispersion in the next lab.
To plot the fitted curves with confidence bands, we use effect() from the effects package. It predicts mortality for each substance along a sequence of doses and returns the confidence limits on the response scale:
dat_effects <- effect("logdose:product", mod = fit2,
xlevels = list(logdose = seq(0.1, 1.7, length.out = 100))) |>
as.data.frame()
ggplot() +
geom_point(data = dat, aes(x = logdose, y = dead/n, col = product)) +
geom_ribbon(data = dat_effects,
aes(x = logdose, ymin = lower, ymax = upper, fill = product),
alpha = 0.2) +
geom_line(data = dat_effects, aes(x = logdose, y = fit, col = product))
The curves for A and C are almost identical and rise steeply from about 0.1 to 0.95. The curve for B is flatter: mortality is higher than for A and C at low doses but lower at high doses, where it reaches only about 0.8. The narrow confidence bands show that this difference is well supported by the data.
Residual analysis
In a GLM, the variance changes with the mean, so raw residuals are hard to compare across fitted values. Three kinds of residuals are common:
- Response residuals: \(r_i = y_i - \hat{\mu}_i\), the raw difference between observed and fitted value.
- Pearson residuals: the response residual divided by the standard deviation the model expects at that fitted value, \(r_i / \sqrt{\text{Var}(\hat{\mu}_i)}\).
- Deviance residuals: each observation’s signed contribution to the model deviance.
For a normal model with identity link, all three are the same. For other GLMs, do not use response residuals to check the model, because their spread changes with the fitted value. Use standardized Pearson residuals instead: rstandard(fit, type = "pearson"). They also account for the leverage of each observation. If the model fits, they scatter around 0 without a pattern, mostly between -2 and 2. (residuals(fit, type = ...) returns the unstandardized versions.)
For fit1, which fits a single curve to all three substances, we plot the standardized Pearson residuals against the fitted mortality:
dat$resid1 <- rstandard(fit1, type = "pearson")
ggplot(dat, aes(x = fitted1, y = resid1, col = product)) +
geom_hline(yintercept = 0) +
geom_hline(yintercept = c(-2, 2), linetype = "dashed") +
geom_point() +
labs(x = "Fitted mortality", y = "Pearson residuals")
Four residuals fall below -2, three of them from product B at high doses: fit1 predicts a higher mortality for B than observed, because it ignores that B levels off. For fit2, which fits a separate curve for each substance, we get the following residuals:
dat$fitted2 <- fitted(fit2)
dat$resid2 <- rstandard(fit2, type = "pearson")
ggplot(dat, aes(x = fitted2, y = resid2, col = product)) +
geom_hline(yintercept = 0) +
geom_hline(yintercept = c(-2, 2), linetype = "dashed") +
geom_point() +
labs(x = "Fitted mortality", y = "Pearson residuals")
With a separate dose-response for each substance, the residuals are centered on 0 for all three products and stay close to the -2 to 2 range.
Judging residual plots by eye is difficult, and for binomial or count data the residuals do not need to be normally distributed. Simulating new data from the fitted model gives a reference for what the residuals should look like (see model checking), and the DHARMa package turns this into standardized residuals for any model type.
Binary response data
We now use a dataset where the response can only take two values, as in dead/alive, presence/absence or conversion/conservation problems. The data indicate whether trees were infested by a bark beetle (1) or not (0), depending on the temperature anomaly (z-transformed temperatures, with values > 0 indicating hotter than average):
dat <- read.csv("data/infestation.csv")
head(dat) infested temp_anomaly
1 1 -1.0785729
2 1 1.2728951
3 1 1.8699789
4 1 0.6327722
5 0 0.3342014
6 1 0.8407184
ggplot(dat, aes(x = temp_anomaly, y = infested)) +
geom_point() +
ylab("Pr(infested)")
The response takes only the values 0 and 1, and infested trees become more common as the temperature anomaly increases. A straight line through these points would predict values below 0 and above 1. Instead, we model the probability of infestation with the logit link, as for the proportion data. Its inverse is an S-shaped curve that is bounded between 0 and 1 and allows a quick transition between the two extremes.
With \(y\) for infestation and \(x\) for the temperature anomaly, the model for the probability of infestation is thus:
\[\Pr(y = 1) = \text{logit}^{-1}(\beta_0 + \beta_1 x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x)}}\]
Each tree is a single trial, so infestation follows a Bernoulli distribution, a binomial distribution with one trial:
\[y \sim \text{Bernoulli}(\text{logit}^{-1}(\beta_0 + \beta_1 x))\]
This model is called binomial logistic regression. For responses with more than two categories, there are multinomial (unordered categories) and ordinal logistic regression (ordered categories). We fit the model with glm():
infested_bin <- glm(infested ~ temp_anomaly,
data = dat,
family = binomial(link = "logit"))
summary(infested_bin)
Call:
glm(formula = infested ~ temp_anomaly, family = binomial(link = "logit"),
data = dat)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.8154 0.5766 1.414 0.15734
temp_anomaly 2.1778 0.7809 2.789 0.00529 **
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 40.381 on 29 degrees of freedom
Residual deviance: 23.488 on 28 degrees of freedom
AIC: 27.488
Number of Fisher Scoring iterations: 5
We plot the fitted probabilities against the temperature anomaly:
newdat <- data.frame(temp_anomaly = seq(-2, 2, length.out = 100))
newdat$fitted <- predict(object = infested_bin,
newdata = newdat,
type = "response")
ggplot() +
geom_point(data = dat, aes(x = temp_anomaly, y = infested)) +
geom_line(data = newdat, aes(x = temp_anomaly, y = fitted)) +
ylab("Pr(infested)")
Confidence intervals by hand
Approximate 95% confidence intervals are the fitted value ± 2 standard errors. We calculate them on the link scale and then back-transform them to the response scale with plogis(), the inverse of the logit:
link_pred <- predict(object = infested_bin, newdata = newdat,
type = "link", se.fit = TRUE)
newdat$fitted_link <- link_pred$fit
newdat$lower_link <- newdat$fitted_link - 2 * link_pred$se.fit
newdat$upper_link <- newdat$fitted_link + 2 * link_pred$se.fit
newdat$lower <- plogis(newdat$lower_link)
newdat$upper <- plogis(newdat$upper_link)We add the confidence band to the plot of the fitted curve:
ggplot() +
geom_point(data = dat, aes(x = temp_anomaly, y = infested)) +
geom_ribbon(data = newdat, aes(x = temp_anomaly, ymin = lower, ymax = upper), alpha = 0.3) +
geom_line(data = newdat, aes(x = temp_anomaly, y = fitted)) +
ylab("Pr(infested)")
Confidence intervals with effects
Alternatively, we can use the effect() function, which does the transformation automatically:
efct <- effect("temp_anomaly",
mod = infested_bin,
xlevels = list(temp_anomaly = seq(-2, 2, length.out = 100))) |>
as.data.frame()
ggplot() +
geom_point(data = dat, aes(x = temp_anomaly, y = infested)) +
geom_ribbon(data = efct, aes(x = temp_anomaly, ymin = lower, ymax = upper), alpha = 0.3) +
geom_line(data = efct, aes(x = temp_anomaly, y = fit)) +
ylab("Pr(infested)")
Interpreting coefficients
Coefficients in logistic regression are harder to interpret than in linear regression. They are linear on the link scale, but the change in probability for a unit change in \(x\) depends on where we are on the curve. Besides plotting the fitted curve, there are several ways to make the coefficients interpretable.
Divide by 4 rule
The divide by 4 rule uses the fact that the logistic curve is steepest at its center, where the linear predictor is zero and the probability is 0.5. The slope of the curve, i.e. the change in probability per unit change in \(x\), is \(\beta_1 \, p \, (1 - p)\). It depends on \(p\) and is largest at \(p = 0.5\), where it is \(\beta_1 \cdot 0.5 \cdot (1 - 0.5) = \beta_1 / 4\). The red line shows the tangent at the 50% point of the fitted bark beetle model, with slope \(\beta_1 / 4\):

Dividing a coefficient by 4 therefore gives an upper bound for the change in probability per unit change in \(x\). The bound is a good approximation near the midpoint of the curve, where probabilities are close to 0.5, and overestimates the change further out. The coefficient of temp_anomaly is 2.18, and \(\frac{2.18}{4} = 0.54\). In a report, this could be written as follows:
The probability of bark beetle infestation increased with the temperature anomaly (logistic regression, \(\beta_1\) = 2.18, SE = 0.78, p = 0.0053). An increase in the temperature anomaly by one standard deviation was associated with an increase in infestation probability of at most 54 percentage points.
Predictor value at 50% probability
A useful summary of a logistic regression is the predictor value at which the probability reaches 50%. In toxicology, this is known as the median lethal dose (LD50). At \(p = 0.5\), the linear predictor is 0, so \(\beta_0 + \beta_1 x = 0\) and \(x_{50} = -\beta_0 / \beta_1\). This is also the point where the curve is steepest and the divide by 4 rule gives the exact slope. The function dose.p() from the MASS package computes this value together with its standard error:
temp_anomaly_p50 <- dose.p(infested_bin, p = 0.5)
temp_anomaly_p50 Dose SE
p = 0.5: -0.3744093 0.2372779
The probability of infestation reaches 50% at a temperature anomaly of about -0.37, i.e. slightly below average temperature (SE 0.24). Together with the divide by 4 rule, this could be reported as follows:
The probability of bark beetle infestation reached 50% at a temperature anomaly of -0.37 (SE = 0.24). At this point, the probability rose most steeply, at a rate of 54 percentage points per standard deviation of the temperature anomaly.
The vertical line marks the 50% point on the fitted curve:
ggplot() +
geom_point(data = dat, aes(x = temp_anomaly, y = infested)) +
geom_hline(yintercept = 0.5, alpha = 0.5) +
geom_vline(xintercept = temp_anomaly_p50, colour = "red") +
geom_line(data = newdat, aes(x = temp_anomaly, y = fitted)) +
ylab("Pr(infested)")
For the toxicity data, the same function gives the LD50. Using fit1, half of the individuals die at a log dose of about 0.69. Because fit1 fits one curve to all three substances, this value is an average over the substances:
dose.p(fit1, p = 0.5) Dose SE
p = 0.5: 0.689395 0.03278104
Odds ratios
Another way to interpret logistic regression coefficients is in terms of odds ratios. If an event has the probability \(p\), its odds are \(p/(1 - p)\), the probability that the event occurs divided by the probability that it does not. Odds of 1 correspond to a probability of 0.5, i.e. both outcomes are equally likely (1:1). Odds of 2 correspond to a probability of 0.67 (2:1), and odds of 0.5 to a probability of 0.33 (1:2).
The odds ratio compares the odds of the same event between two groups or conditions:
\[\text{OR} = \frac{p_1/(1 - p_1)}{p_2/(1 - p_2)}\]
An odds ratio above 1 means the event is more likely in the first group, below 1 that it is less likely, and equal to 1 that there is no difference.
In logistic regression, the logit link is the log of the odds, \(\log(p/(1-p))\), so a coefficient gives the change in log-odds per unit change in the predictor. Exponentiating the coefficient turns it into an odds ratio:
\[ \frac{\text{odds}(x + 1)}{\text{odds}(x)} = \frac{e^{\beta_0 + \beta_1 (x + 1)}}{e^{\beta_0 + \beta_1 x}} = e^{\beta_1} \]
For a continuous predictor, \(e^{\beta_1}\) is the odds ratio for a one-unit increase. For a categorical predictor, it compares each level with the reference level.
Example: plant occurrence
A plant species was observed in 6 of 10 plots in landscape A and in 4 of 10 plots in landscape B, which gives probabilities of 0.6 and 0.4. The odds ratio of observing the plant in landscape A compared to landscape B is \(\text{OR} = \frac{0.6/0.4}{0.4/0.6} = 2.25\). The odds of observing the plant are thus 2.25 times higher in landscape A than in landscape B.
Example: bark beetle infestation
We exponentiate the coefficient of temp_anomaly and its confidence interval:
odds_ratio <- exp(coef(infested_bin)[2])
odds_ratio_ci <- exp(confint(infested_bin)[2, ])
odds_ratiotemp_anomaly
8.826474
odds_ratio_ci 2.5 % 97.5 %
2.578221 64.461800
In a report, this could be written as follows:
The odds of bark beetle infestation increased with the temperature anomaly. A one standard deviation increase in the temperature anomaly was associated with 8.8 times higher odds of infestation (odds ratio, 95% CI: 2.6 to 64.5).
The wide confidence interval reflects the small sample of 30 trees: the direction of the effect is clear, but its size is uncertain.