Skip to main content

Splines and GAMs: At What Temperature Do the Fewest People Die?

Splines and generalized additive models (GAM) in R with mgcv, on 14 years of daily deaths and temperature in Chicago (1987-2000): basis functions, penalized splines by hand, effective degrees of freedom, GCV and REML, confounding by season, delayed effects, negative binomial outcomes, relative risks and the temperature of least mortality with intervals, checks of the basis, concurvity, autocorrelation, the 1995 heat wave and APA reporting.

The question: too cold, too hot, and in between

People die of heat, and people die of cold. Between the two there must be a temperature at which the fewest people die. What is it? And how much worse are the extremes?

No formula is known for this curve. It should be high on the left, low in the middle and high on the right, but it need not be a parabola: heat may act suddenly above some threshold, and cold slowly. So we want a method that finds the shape by itself. But we also need more than a smooth line through a cloud of points (as LOESS gives). In winter there are also influenza, short days and indoor air. The season must be in the model next to the temperature, like a covariate in a regression.

Splines are flexible curves made of ordinary regression columns. A generalized additive model (GAM) is a regression in which some predictors enter as splines:

\[\log E(\text{deaths}) = \beta_0 + s_1(\text{temperature}) + s_2(\text{time}) + \text{day of the week}\]

Each \(s\) is a smooth curve whose shape and wiggliness are estimated from the data. The rest is a generalized linear model, as in this page.

Code
library(ggplot2)
library(mgcv)      # gam(): generalized additive models (comes with R)
library(splines)   # bs(), ns(): spline columns for any regression (comes with R)

# number formats for the text
f1   <- function(x) formatC(x, format = "f", digits = 1, big.mark = ",")
f2   <- function(x) formatC(x, format = "f", digits = 2, big.mark = ",")
f3   <- function(x) formatC(x, format = "f", digits = 3, big.mark = ",")
# no leading zero
nz <- function(x, d = 2) sub("^(-?)0", "\\1", formatC(x, format = "f", digits = d))
pval <- function(p) if (p < .001) "< .001" else paste("=", nz(p, 3))
num  <- function(x) trimws(format(x, big.mark = ","))

1. The data

The data are the daily deaths in Chicago (accidents excluded) and the weather and air pollution of each day, from 1987 to 2000. They come from a large American study of mortality and air pollution (Samet et al., 2000), and the authors of the R package dlnm distribute them:

Code
path <- tempfile(fileext = ".rda")
download.file("https://raw.githubusercontent.com/gasparrini/dlnm/master/data/chicagoNMMAPS.rda",
              path, mode = "wb", quiet = TRUE)
load(path)
chicago <- chicagoNMMAPS[, c("date", "time", "dow", "death", "temp")]
nrow(chicago)
[1] 5114
Code
summary(chicago[, c("death", "temp")])
     death            temp        
 Min.   : 69.0   Min.   :-26.667  
 1st Qu.:105.0   1st Qu.:  1.667  
 Median :114.0   Median : 10.556  
 Mean   :115.4   Mean   : 10.107  
 3rd Qu.:124.0   3rd Qu.: 19.444  
 Max.   :411.0   Max.   : 33.333  
Code
chicago[order(-chicago$death), ][1:5, ]
           date time      dow death       temp
3118 1995-07-15 3118 Saturday   411 30.0000000
3119 1995-07-16 3119   Sunday   287 28.3333333
3120 1995-07-17 3120   Monday   228 25.8333333
3117 1995-07-14 3117   Friday   226 33.0555556
1096 1989-12-31 1096   Sunday   186 -0.8333333

There are 5,114 days. death is the number of deaths, temp the mean temperature of the day in °C, dow the day of the week and time counts the days. An average day has 115.4 deaths. The worst days are in July 1995: a heat wave, with 411 deaths on one day.

Cold may take days to act, for example through infections. So we also compute the mean temperature of the seven days before each day:

Code
# mean of today and the 6 days before
running <- as.numeric(stats::filter(chicago$temp, rep(1 / 7, 7), sides = 1))
chicago$week <- c(NA, running[-length(running)]) # moved by one day: the 7 days before today
chicago <- subset(chicago, !is.na(week))
nrow(chicago)
[1] 5107

2. Look at the data

Code
pa <- ggplot(chicago, aes(date, death)) +
  geom_point(size = 0.5, alpha = 0.4, colour = "grey30") +
  labs(title = "Deaths per day", x = NULL, y = "deaths") + theme_bw()
pb <- ggplot(chicago, aes(temp, death)) +
  geom_point(size = 0.5, alpha = 0.3, colour = "grey30") +
  coord_cartesian(ylim = c(60, 240)) +
  labs(
    title = "Deaths against the temperature of the day",
    subtitle = "Two days with more than 240 deaths are outside the chart",
    x = "temperature (°C)",
    y = "deaths"
  ) +
  theme_bw()
patchwork::wrap_plots(pa, pb, ncol = 1)

Plot: 2. Look at the data

The first chart shows the seasons: every winter is a hill. The second one falls with the temperature, and turns up at the hot end. But part of the fall may be the winter itself, and not the cold.


3. Splines step by step, with formulas

Step 1: polynomials in pieces

Cut the range of the temperature at some points, the knots, and use a cubic polynomial in each piece, joined so smoothly that the eye does not see the joints: equal value, slope and curvature on both sides. That is a cubic spline. It can bend where it is needed, and a bend on one side does not disturb the other side, as it would in a polynomial.

Step 2: a spline is a sum of columns

Any cubic spline can be written as a weighted sum of fixed curves, the basis functions:

\[s(x) = \sum_{j=1}^{K} \beta_j\, B_j(x)\]

So once the knots are fixed, a spline is a linear model: each \(B_j(x)\) is a column, and least squares finds the \(\beta\)’s. The basis of B-splines has functions that are zero except over a few pieces:

Code
grid  <- seq(min(chicago$temp), max(chicago$temp), length.out = 300)
knots <- seq(-27, 34, length.out = 9)                                  # 8 pieces, for the drawing
B     <- splineDesign(c(rep(knots[1], 3), knots, rep(knots[9], 3)), grid, outer.ok = TRUE)
basis <- data.frame(
  temp = grid,
  value = as.vector(B),
  j = factor(rep(seq_len(ncol(B)), each = length(grid)))
)

ggplot(basis, aes(temp, value, group = j)) +
  geom_line(aes(colour = j), linewidth = 0.8) +
  geom_vline(xintercept = knots, linetype = "dotted", colour = "grey60") +
  guides(colour = "none") +
  labs(title = paste(ncol(B), "B-spline basis functions (the dotted lines are the knots)"),
       x = "temperature (°C)", y = "value of the column") +
  theme_bw()

Basis – Step 2: a spline is a sum of columns

Step 3: how many knots? Use many, and pay for the wiggles

With few knots the curve is stiff, with many it follows the noise. And where to put them? The modern answer is: take more than enough knots, and add a penalty for wiggliness to the sum of squares:

\[\sum_i \big[y_i - s(x_i)\big]^2 + \lambda \int s''(x)^2\, dx\]

\(s''\) is the curvature. \(\lambda\) decides the price: with \(\lambda = 0\) we get the wild curve of all the knots, with \(\lambda \to \infty\) a straight line. The penalty is a quadratic form in the coefficients, \(\lambda\, \beta^\top S \beta\), so the solution is still a formula, like ridge regression:

\[\hat\beta = (B^\top B + \lambda S)^{-1} B^\top y\]

For B-splines with equally spaced knots, a simple and good \(S\) makes neighboring coefficients differ smoothly. It is built from their second differences (P-splines; Eilers & Marx, 1996):

Code
x <- chicago$temp; y <- chicago$death
n_basis <- 20
step  <- (max(x) - min(x)) / (n_basis - 3)
# equally spaced knots, beyond the ends too
ts <- seq(min(x) - 3 * step, max(x) + 3 * step, by = step)
B_    <- splineDesign(ts, x, outer.ok = TRUE)
D <- diff(diag(ncol(B_)), differences = 2) # second differences of the coefficients
S     <- crossprod(D)
fit_by_hand <- function(lambda) {
  A    <- solve(crossprod(B_) + lambda * S)
  beta <- A %*% crossprod(B_, y)
  edf  <- sum(diag(A %*% crossprod(B_)))                             # effective degrees of freedom
  rss  <- sum((y - B_ %*% beta)^2)
  list(beta = beta, edf = edf, GCV = length(y) * rss / (length(y) - edf)^2)
}
lambdas <- 10^seq(-2, 7, by = 0.25)
trials  <- lapply(lambdas, fit_by_hand)
gcv     <- sapply(trials, `[[`, "GCV")
best    <- which.min(gcv)
c(best_lambda = lambdas[best], edf = trials[[best]]$edf)
best_lambda         edf 
   3.162278   12.689426 

Step 4: effective degrees of freedom

The penalty ties the coefficients together, so 20 columns do not count as 20 parameters. The effective degrees of freedom (edf), the trace of the matrix that turns \(y\) into \(\hat y\), count how many parameters the curve really uses: 2 for a straight line, 20 for the unpenalized spline, and here 12.7.

Step 5: choosing \(\lambda\)

By hand we took the \(\lambda\) with the smallest GCV (generalized cross-validation), which imitates leaving out one day at a time. mgcv can do the same. The better default today is REML: the penalty is read as a statement that the coefficients come from a normal distribution, and \(\lambda\) becomes a variance ratio that is estimated like that of a mixed model. REML overfits less often (Wood, 2011).

Code
shown <- c(which(lambdas == 10^-2), best, length(lambdas))
B_grid <- splineDesign(ts, grid, outer.ok = TRUE)
curves <- do.call(
  rbind,
  lapply(shown, function(k) {
    data.frame(
      temp = grid,
      death = drop(B_grid %*% trials[[k]]$beta),
      label = sprintf(
        "λ = %s, edf = %.1f",
        format(lambdas[k], big.mark = ",", scientific = FALSE, digits = 2),
        trials[[k]]$edf
      )
    )
  })
)
curves$label <- factor(curves$label, levels = unique(curves$label))

ggplot(chicago, aes(temp, death)) +
  geom_point(size = 0.4, alpha = 0.15, colour = "grey40") +
  geom_line(data = curves, aes(colour = label), linewidth = 1) +
  scale_colour_manual(values = c("#eda100", "#2a78d6", "#eb6834"), name = NULL) +
  coord_cartesian(ylim = c(80, 200)) +
  labs(
    title = "Too little penalty, the GCV choice, and too much",
    x = "temperature (°C)",
    y = "deaths"
  ) +
  theme_bw() +
  theme(legend.position = "bottom")

Lambda chart – Step 5: choosing λ

Code
same <- gam(death ~ s(temp, bs = "ps", k = n_basis), data = chicago, method = "GCV.Cp")
c(edf_by_hand = trials[[best]]$edf, edf_mgcv = sum(same$edf))
edf_by_hand    edf_mgcv 
   12.68943    12.91523 

The same P-spline in mgcv has 12.9 edf: our grid of \(\lambda\) was only a little coarser than its search.

Step 6: from one spline to a GAM

A GAM puts several splines side by side, each with its own \(\lambda\), and a link function and distribution around them. The counts of deaths vary a bit more than a Poisson distribution allows, so we use the negative binomial (family = nb), which adds one parameter for the extra variation. The \(s\) curves are centered: each has mean zero over the data, and the intercept takes the level.


4. Fitting the models and reading the output

Model A: temperature alone

Code
model_a <- gam(death ~ s(temp) + dow, family = nb, data = chicago, method = "REML")
summary(model_a)

Family: Negative Binomial(198.233) 
Link function: log 

Formula:
death ~ s(temp) + dow

Parametric coefficients:
             Estimate Std. Error  z value Pr(>|z|)    
(Intercept)  4.728910   0.004362 1084.225  < 2e-16 ***
dowMonday    0.034737   0.006136    5.661 1.51e-08 ***
dowTuesday   0.027201   0.006144    4.427 9.55e-06 ***
dowWednesday 0.009819   0.006160    1.594 0.110926    
dowThursday  0.012516   0.006155    2.033 0.042007 *  
dowFriday    0.019083   0.006150    3.103 0.001916 ** 
dowSaturday  0.022355   0.006147    3.637 0.000276 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
          edf Ref.df Chi.sq p-value    
s(temp) 7.705  8.502   1115  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.178   Deviance explained = 18.9%
-REML =  20513  Scale est. = 1         n = 5107
  • Parametric coefficients are as in any GLM with a log link: \(e^{0.035}\) = 1.035, so Mondays have 3.5% more deaths than Sundays.
  • edf of s(temp) = 7.7: how wiggly the curve is. 1 would be a straight line.
  • p-value of a smooth tests whether the whole curve is flat. It is approximate, and with 5,107 days nearly everything is “significant”. Look at the curve instead.
  • Deviance explained plays the role of \(R^2\): 18.9%.

There is no table of coefficients for the curve. It has coefficients, but nobody reads them. A smooth is read as a picture.

Model B: add the season and the long-term trend

The smooth of time follows the slow changes from 1987 to 2000: winters, summers, a changing population. With 14 years and about 10 degrees of freedom a year it can follow the seasons but not single days: k = 150 gives it room, and REML decides how much to use.

Code
model_b <- gam(
  death ~ s(temp) + s(time, k = 150) + dow,
  family = nb,
  data = chicago,
  method = "REML"
)
summary(model_b)$s.table
               edf     Ref.df   Chi.sq p-value
s(temp)   7.288273   8.214878  154.777       0
s(time) 106.959544 125.862132 1333.443       0
Code
c(deviance_explained = summary(model_b)$dev.expl)
deviance_explained 
         0.3771583 

Model C: add the week before

Code
model_c <- gam(
  death ~ s(temp) + s(week) + s(time, k = 150) + dow,
  family = nb,
  data = chicago,
  method = "REML"
)
summary(model_c)$s.table
              edf     Ref.df   Chi.sq p-value
s(temp)  6.924380   7.938209 177.1123       0
s(week)  8.553357   8.933656 209.4865       0
s(time) 93.933745 113.094755 801.6846       0
Code
c(deviance_explained = summary(model_c)$dev.expl)
deviance_explained 
         0.3927253 
Code
AIC(model_a, model_b, model_c)
               df      AIC
model_a  16.02954 40953.02
model_b 123.88909 39858.20
model_c 119.87738 39724.88

The AIC falls by 1,094.8 when the season enters, and by another 133.3 with the week before. What happens to the temperature curve?

Code
# the curve of one or more smooths (in % of deaths, relative to the average of the curve), with its
# 95% band
curve_of <- function(model, terms, newdata) {
  X <- predict(model, newdata, type = "lpmatrix") # the columns of the model at these values
  # keep only these terms
  X[, !grepl(paste(gsub("([()])", "\\\\\\1", terms), collapse = "|"), colnames(X))] <- 0
  fit <- drop(X %*% coef(model))
  se <- sqrt(rowSums((X %*% vcov(model)) * X))
  data.frame(
    newdata,
    fit = 100 * (exp(fit) - 1),
    low = 100 * (exp(fit - 1.96 * se) - 1),
    high = 100 * (exp(fit + 1.96 * se) - 1)
  )
}
at <- data.frame(temp = seq(-22, 32, by = 0.5))
at$week <- 10
at$time <- 2500
at$dow <- "Wednesday" # the other terms are set to zero anyway
three <- rbind(cbind(curve_of(model_a, "s(temp)", at), model = "A: temperature alone"),
               cbind(curve_of(model_b, "s(temp)", at), model = "B: + season and trend"),
               cbind(curve_of(model_c, "s(temp)", at), model = "C: + the week before"))
Code
ggplot(three, aes(temp, fit)) +
  geom_hline(yintercept = 0, colour = "grey60") +
  geom_ribbon(aes(ymin = low, ymax = high), fill = "#2a78d6", alpha = 0.2) +
  geom_line(colour = "#2a78d6", linewidth = 1) +
  facet_wrap(~ model) +
  labs(title = "Temperature of the day and deaths: s(temp) in the three models",
       x = "temperature of the day (°C)", y = "deaths, % above or below the average") +
  theme_bw()

Temperature curves – Model C: add the week before

Code
low_point <- sapply(split(three, three$model), function(d) d$temp[which.min(d$fit)])
low_point
 A: temperature alone B: + season and trend  C: + the week before 
                 21.5                   3.5                 -22.0 
Code
at_cold <- sapply(split(three, three$model), function(d) d$fit[d$temp == -15])

Alone (A), the curve is the one everybody expects: high in the cold, lowest at 21.5 °C, and up in the heat. But once the season is in the model (B), the cold side disappears: on a day of −15 °C the curve is at -2.4%, against 10.4% before. A cold day is not deadlier than a mild day of the same season. The heat side stays. The smooth of the week before shows where the cold went:

Code
at_week <- data.frame(week = seq(-17, 28, by = 0.5), temp = 10, time = 2500, dow = "Wednesday")
week <- curve_of(model_c, "s(week)", at_week)

ggplot(week, aes(week, fit)) +
  geom_hline(yintercept = 0, colour = "grey60") +
  geom_ribbon(aes(ymin = low, ymax = high), fill = "#1baf7a", alpha = 0.2) +
  geom_line(colour = "#1baf7a", linewidth = 1) +
  labs(
    title = "The week before and deaths: s(week) in model C",
    x = "mean temperature of the seven days before (°C)",
    y = "deaths, % above or below the average"
  ) +
  theme_bw()

Week curve – Model C: add the week before

After a cold week more people die. Heat kills at once, cold kills with a delay. With the temperature of one day only, and the season as a smooth, the delayed effect of cold was taken for season.


5. The answer: the temperature with the fewest deaths

The question is about a temperature that lasts: a week and a day at the same temperature. In the additive model this is the sum of the two curves, \(s_1(x) + s_2(x)\), at the same \(x\). We compute it for a grid, find its lowest point, and express everything relative to it, as a relative risk (RR). The uncertainty of a difference between two points of a curve comes from the model matrix and the covariance matrix of the coefficients:

\[\log \text{RR}(x) = (X_x - X_{\min})\,\hat\beta, \qquad SE = \sqrt{(X_x - X_{\min})\, V\, (X_x - X_{\min})^\top}\]

Code
lasting <- function(model, from = -20, to = 31) {
  g <- data.frame(temp = seq(from, to, by = 0.5))
  g$week <- g$temp
  g$time <- 2500
  g$dow <- "Wednesday"
  X <- predict(model, g, type = "lpmatrix")
  X[, !grepl("s\\(temp\\)|s\\(week\\)", colnames(X))] <- 0
  f <- drop(X %*% coef(model))
  i <- which.min(f)
  d <- sweep(X, 2, X[i, ]) # each row minus the row of the minimum
  logrr <- drop(d %*% coef(model))
  se <- sqrt(rowSums((d %*% vcov(model)) * d))
  set.seed(3)
  draws <- rmvn(2000, coef(model), vcov(model)) # 2,000 curves that are compatible with the data
  minima <- g$temp[apply(X %*% t(draws), 2, which.min)]
  list(
    curve = data.frame(
      temp = g$temp,
      rr = exp(logrr),
      low = exp(logrr - 1.96 * se),
      high = exp(logrr + 1.96 * se)
    ),
    minimum = g$temp[i],
    interval = quantile(minima, c(0.025, 0.975))
  )
}
answer <- lasting(model_c)
rr <- function(t) answer$curve[answer$curve$temp == t, ]
c(minimum = answer$minimum, answer$interval)
minimum    2.5%   97.5% 
   22.5    22.0    23.0 
Code
round(rbind(rr(-15), rr(-10), rr(0), rr(10), rr(28), rr(30)), 3)
    temp    rr   low  high
11   -15 1.166 1.118 1.216
21   -10 1.137 1.097 1.179
41     0 1.087 1.055 1.120
61    10 1.043 1.020 1.067
97    28 1.177 1.143 1.212
101   30 1.316 1.254 1.381
Code
ggplot(answer$curve, aes(temp, rr)) +
  geom_hline(yintercept = 1, colour = "grey60") +
  geom_ribbon(aes(ymin = low, ymax = high), fill = "#2a78d6", alpha = 0.2) +
  geom_line(colour = "#2a78d6", linewidth = 1) +
  geom_vline(xintercept = answer$minimum, linetype = "dashed", colour = "#eb6834") +
  labs(title = "Relative risk of death when a temperature lasts a week and a day",
       subtitle = "Compared with the temperature with the fewest deaths (dashed line)",
       x = "temperature (°C)", y = "relative risk") +
  theme_bw()

Combined chart – 5. The answer: the temperature with the fewest deaths

  • The fewest people die at 22.5 °C, with an interval from 22 to 23 °C (from 2,000 simulated curves).
  • At 30 °C the risk is 1.32 times as high, 95% CI [1.25, 1.38]. At −15 °C, 1.17 times, [1.12, 1.22].
  • The two sides have different shapes: the cold side rises slowly over 40 degrees, the hot side turns up sharply above about 25 °C. A parabola would have missed both.

6. Checking the model

Was the basis large enough?

k is the upper limit of the wiggliness. If the edf come close to it, the curve was cut short, and k should be raised:

Code
k.check(model_c)
         k'       edf   k-index p-value
s(temp)   9  6.924380 0.9997614  0.4975
s(week)   9  8.553357 0.9912516  0.2875
s(time) 149 93.933745 0.9198874  0.0000

k' is the limit and edf what was used. The smooths of temperature are near their limit of 9, so we double the limit and see if the answer changes:

Code
model_k <- gam(
  death ~ s(temp, k = 20) + s(week, k = 20) + s(time, k = 150) + dow,
  family = nb,
  data = chicago,
  method = "REML"
)
answer_k <- lasting(model_k)
rbind(
  k10 = c(edf = summary(model_c)$s.table[1:2, "edf"], minimum = answer$minimum, AIC = AIC(model_c)),
  k20 = c(
    edf = summary(model_k)$s.table[1:2, "edf"],
    minimum = answer_k$minimum,
    AIC = AIC(model_k)
  )
)
    edf.s(temp) edf.s(week) minimum      AIC
k10    6.924380    8.553357    22.5 39724.88
k20    8.672946   14.819002    23.5 39698.30

The minimum moves from 22.5 to 23.5 °C, and the AIC changes by -26.6. So the simulated interval of section 5 was too narrow: it takes the basis as given. The smooth of time fails the test of k.check (its p value is small), which brings us to the next point.

Autocorrelation

Code
lag1 <- sapply(list(A = model_a, B = model_b, C = model_c), function(m) {
  acf(resid(m, type = "pearson"), plot = FALSE)$acf[2]
})
lag1
        A         B         C 
0.2868245 0.1248022 0.1080386 

The residuals of neighboring days correlate at 0.29 in model A and 0.11 in model C. What is left is small, but it makes the bands a little too narrow. If time were given many more degrees of freedom, it would take it all, and with it part of the effect of temperature. How smooth the season should be is a judgment in this kind of study, and the honest thing is to vary it:

Code
season <- do.call(
  rbind,
  lapply(c(30, 60, 100, 150, 200), function(k) {
    m <- gam(
      death ~ s(temp) + s(week) + s(time, k = k) + dow,
      family = nb,
      data = chicago,
      method = "REML"
    )
    a <- lasting(m)
    data.frame(
      k,
      edf_time = summary(m)$s.table["s(time)", "edf"],
      minimum = a$minimum,
      RR_cold = a$curve$rr[a$curve$temp == -15],
      RR_hot = a$curve$rr[a$curve$temp == 30],
      AIC = AIC(m)
    )
  })
)
round(season, 2)
    k edf_time minimum RR_cold RR_hot      AIC
1  30    24.49    22.5    1.28   1.31 40067.11
2  60    43.64    22.5    1.26   1.32 39977.34
3 100    75.78    22.5    1.18   1.31 39787.67
4 150    93.93    22.5    1.17   1.32 39724.88
5 200   100.06    22.5    1.16   1.32 39713.10

The lowest point and the hot side do not depend on it. The cold side does: the relative risk at −15 °C goes from 1.28 with a stiff season to 1.16 with a flexible one. Heat comes in short bursts that no season can imitate; cold lasts, and shares its time with the winter.

Concurvity

In a GAM two smooths can carry the same information, as correlated predictors do. It is called concurvity, on a scale from 0 to 1:

Code
round(concurvity(model_c, full = FALSE)$estimate, 2)
        para s(temp) s(week) s(time)
para       1    0.00    0.00    0.00
s(temp)    0    1.00    0.73    0.00
s(week)    0    0.71    1.00    0.01
s(time)    0    0.73    0.85    1.00

Each column says how much of the smooth could be explained by the one in the row. The temperatures of the day and of the week before overlap, as they must, which makes their separate curves less certain than their sum. And the smooth of time could explain most of the weekly temperature, because the season sets it: what the model calls the effect of a cold week is learned from weeks that were colder than usual for their season.

The heat wave of July 1995

One week may decide the hot side of the curve. Without the week of 13 to 19 July 1995:

Code
no_wave  <- subset(chicago, date < as.Date("1995-07-13") | date > as.Date("1995-07-19"))
model_w <- gam(
  death ~ s(temp) + s(week) + s(time, k = 150) + dow,
  family = nb,
  data = no_wave,
  method = "REML"
)
answer_w <- lasting(model_w)
rr_w <- function(t) answer_w$curve[answer_w$curve$temp == t, ]
rbind(with_the_week = rr(30), without_it = rr_w(30))
              temp       rr      low     high
with_the_week   30 1.316046 1.254072 1.381083
without_it      30 1.141997 1.094650 1.191393
Code
c(minimum_without_it = answer_w$minimum)
minimum_without_it 
                22 

The relative risk at 30 °C falls from 1.32 to 1.14. Both numbers are true, and they answer different questions: the second is the risk of a hot week, the first includes one catastrophe. The lowest point moves only from 22.5 to 22 °C.


7. Splines without penalties, and other choices

Splines are just columns, so they work in any regression function. ns(x, df) makes a natural cubic spline, which is a straight line beyond the last knots, and is the usual choice when the number of degrees of freedom is fixed in advance:

Code
glm_ns <- glm(
  death ~ ns(temp, df = 4) + ns(week, df = 4) + ns(time, df = 7 * 14) + dow,
  family = quasipoisson,
  data = chicago
)
g <- data.frame(temp = seq(-20, 31, by = 0.5))
g$week <- g$temp
g$time <- 2500
g$dow <- "Wednesday"
p_ns <- predict(glm_ns, g)
g$temp[which.min(p_ns)]
[1] 18.5

With 4 degrees of freedom for each temperature and 7 per year for the season, the lowest point is at 18.5 °C, against 22.5 °C: four degrees of freedom are too stiff for the sharp turn at the hot end. This is the weakness of fixed degrees of freedom. The result depends on a number that somebody had to choose, and the penalized model estimates it.

Polynomial LOESS Spline, fixed df Penalized spline (GAM)
Wiggliness set by degree span number of knots estimated (REML)
Other predictors yes hardly yes yes
Other outcomes (counts, yes/no) yes no yes yes
Tests, intervals exact approximate exact approximate
At the ends wild unstable natural: straight straight-ish

8. Things to keep in mind

  • Additive means that the curve of one predictor is the same at all values of the others. If heat is worse after a hot week, the model needs an interaction, a surface: te(temp, week).
  • Beyond the data, a penalized spline continues roughly straight. It is an extrapolation like any other.
  • edf is not the number of bends, and the p value of a smooth does not say where the curve matters. Report the picture with its band, and differences between meaningful points.
  • The band is pointwise, for the curve around its mean. For a difference from a reference point, use the model matrix as in section 5: the band is zero wide at the reference.
  • Delays. We used one day and one week. Distributed lag models (dlnm) estimate a curve for every delay (Gasparrini, 2011).
  • Not causal by itself. Influenza epidemics come in cold weeks, and the smooth of time cannot remove an epidemic of two weeks. Part of the “cold” curve may be influenza.
  • Deaths of one city say what the city is used to. Such curves differ between climates: people in warm places are hurt by cold that others do not notice (Curriero et al., 2002).
  • Speed. For large data use bam() instead of gam().

9. Reporting the results in APA style

A report (APA 7th edition) needs the family and link, every smooth with its basis dimension, how the smoothness was chosen, the edf, the picture, and some numbers read from the curve. The numbers come from the R objects:

Code
st <- summary(model_c)$s.table
apa_table <- data.frame(
  Smooth = c("Temperature of the day", "Mean temperature of the 7 days before", "Time"),
  k      = c(10, 10, 150),
  edf    = f1(st[, "edf"]),
  chi    = f1(st[, "Chi.sq"]),
  p      = sapply(st[, "p-value"], function(p) sub("^= ", "", pval(p))))
rr_table <- data.frame(t = c(-15, -10, 0, 10, 20, 25, 28, 30))
rr_table <- cbind(
  rr_table,
  answer$curve[match(rr_table$t, answer$curve$temp), c("rr", "low", "high")]
)

Method (data analysis):

We modeled the daily number of deaths (accidents excluded) in Chicago from 1987 to 2000 (N = 5,107 days) with a generalized additive model with a negative binomial distribution and a log link. The predictors were smooth functions (thin plate regression splines; Wood, 2017) of the mean temperature of the day, of the mean temperature of the seven preceding days and of time (basis dimension 150, for season and trend), and the day of the week. Smoothness was selected by restricted maximum likelihood (REML). The relative risk of a temperature that lasts is the sum of the two temperature curves, relative to the temperature at which it is lowest; its confidence interval is based on the covariance matrix of the coefficients, and that of the temperature of minimum mortality on 2,000 simulations from their distribution. Analyses were conducted in R (Version 4.6.2; R Core Team, 2026) with the package mgcv (Wood, 2017).

Results:

Deaths were related to the temperature of the day and to that of the preceding week (Table 1); the model explained 39.3% of the deviance. The temperature with the lowest mortality was 22.5 °C, 95% CI [22.0, 23.0]. Compared with it, the relative risk was 1.17, 95% CI [1.12, 1.22], at −15 °C and 1.32, 95% CI [1.25, 1.38], at 30 °C (Table 2). Without the heat wave of 13–19 July 1995 the relative risk at 30 °C was 1.14, 95% CI [1.09, 1.19]. The lag-1 autocorrelation of the residuals was 0.11.

Table 1

Smooth Terms of the Model of Daily Deaths

Smooth Basis dimension edf χ² p
Temperature of the day 10 6.9 177.1 < .001
Mean temperature of the 7 days before 10 8.6 209.5 < .001
Time 150 93.9 801.7 < .001

Note. N = 5,107 days. edf = effective degrees of freedom. The p values are approximate. The model also contains the day of the week.

Table 2

Relative Risk of Death by Temperature

Temperature (°C) Relative risk 95% CI
-15 1.17 [1.12, 1.22]
-10 1.14 [1.10, 1.18]
0 1.09 [1.05, 1.12]
10 1.04 [1.02, 1.07]
20 1.02 [1.01, 1.03]
25 1.03 [1.02, 1.04]
28 1.18 [1.14, 1.21]
30 1.32 [1.25, 1.38]

Note. Compared with 22.5 °C. The same temperature on the day and in the seven days before.

Points to remember:

  • Report the family, the link, the basis and its dimension, and the method for the smoothness.
  • Show the curves with their bands. Do not interpret edf.
  • Turn the curve into numbers at values that mean something.
  • Say how the results change with the choices: basis dimension, smoothness of the season, unusual days.

10. Summary

When The relation is smooth, its shape is unknown, and there are other predictors
Spline A sum of basis functions, \(\sum \beta_j B_j(x)\): a linear model with special columns
Penalty \(\lambda \int s''^2\): more than enough knots, and a price for wiggles
edf How many parameters the penalized curve really uses
How (R) gam(y ~ s(x1) + s(x2, k = 20) + z, family = , method = "REML"); fixed df: glm(y ~ ns(x, 4))
Reading it Pictures with bands; differences from predict(..., type = "lpmatrix")
Checks k.check(), gam.check(), residual autocorrelation, concurvity()
Related pages LOESS, polynomial regression, generalized linear models

References

Curriero, F. C., Heiner, K. S., Samet, J. M., Zeger, S. L., Strug, L., & Patz, J. A. (2002). Temperature and mortality in 11 cities of the eastern United States. American Journal of Epidemiology, 155(1), 80–87. https://doi.org/10.1093/aje/155.1.80

Eilers, P. H. C., & Marx, B. D. (1996). Flexible smoothing with B-splines and penalties. Statistical Science, 11(2), 89–121. https://doi.org/10.1214/ss/1038425655

Gasparrini, A. (2011). Distributed lag linear and non-linear models in R: The package dlnm. Journal of Statistical Software, 43(8), 1–20. https://doi.org/10.18637/jss.v043.i08

Samet, J. M., Dominici, F., Curriero, F. C., Coursac, I., & Zeger, S. L. (2000). Fine particulate air pollution and mortality in 20 U.S. cities, 1987–1994. The New England Journal of Medicine, 343(24), 1742–1749. https://doi.org/10.1056/NEJM200012143432401

Wood, S. N. (2011). Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalized linear models. Journal of the Royal Statistical Society: Series B, 73(1), 3–36. https://doi.org/10.1111/j.1467-9868.2010.00749.x

Wood, S. N. (2017). Generalized additive models: An introduction with R (2nd ed.). CRC Press. https://doi.org/10.1201/9781315370279