---
title: "Splines and GAMs: At What Temperature Do the Fewest People Die?"
description: "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."
author: ""
---
```{r options, echo=FALSE, warning=FALSE, message=FALSE}
directory<-if (rstudioapi::isAvailable()) paste0(dirname(rstudioapi::getActiveDocumentContext()$path),"/") else ""
source(paste0(directory, "R/code_options.R"))
# no knitr cache: the page downloads its data each time it runs (in about a second),
# and a cached chunk would quietly keep an old download
knitr::opts_chunk$set(fig.height = 4.5, cache = FALSE)
```
## 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](EXAMPLE_LOESS.Rmd) 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](EXAMPLE_GENERALIZED.rmd).
```{r packages}
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:
```{r download}
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)
summary(chicago[, c("death", "temp")])
chicago[order(-chicago$death), ][1:5, ]
```
There are `r num(nrow(chicago))` 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 `r f1(mean(chicago$death))` deaths. The worst days are in **July 1995**: a heat wave, with `r max(chicago$death)` 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:
```{r lag}
# 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)
```
---
## 2. Look at the data
```{r look, fig.height = 6.5}
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)
```
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](EXAMPLE_POLYNOMIAL_REGRESSION.Rmd).
### 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:
```{r basis}
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()
```
### 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](EXAMPLE_REGULARIZED_REGRESSION.Rmd):
$$\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):
```{r by_hand}
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)
```
### Step 4: effective degrees of freedom
The penalty ties the coefficients together, so `r n_basis` columns do not count as `r n_basis` 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, `r n_basis` for the unpenalized spline, and here `r f1(trials[[best]]$edf)`.
### 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](EXAMPLE_MULTILEVEL.Rmd). REML overfits less often (Wood, 2011).
```{r lambda_chart}
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")
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))
```
The same P-spline in `mgcv` has `r f1(sum(same$edf))` 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
```{r model_a}
model_a <- gam(death ~ s(temp) + dow, family = nb, data = chicago, method = "REML")
summary(model_a)
```
- **`Parametric coefficients`** are as in any GLM with a log link: $e^{`r f3(coef(model_a)[["dowMonday"]])`}$ = `r f3(exp(coef(model_a)[["dowMonday"]]))`, so Mondays have `r f1(100 * (exp(coef(model_a)[["dowMonday"]]) - 1))`% more deaths than Sundays.
- **`edf`** of `s(temp)` = `r f1(summary(model_a)$edf)`: 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 `r num(nrow(chicago))` days nearly everything is "significant". Look at the curve instead.
- **`Deviance explained`** plays the role of $R^2$: `r f1(100 * summary(model_a)$dev.expl)`%.
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.
```{r model_b}
model_b <- gam(
death ~ s(temp) + s(time, k = 150) + dow,
family = nb,
data = chicago,
method = "REML"
)
summary(model_b)$s.table
c(deviance_explained = summary(model_b)$dev.expl)
```
### Model C: add the week before
```{r model_c}
model_c <- gam(
death ~ s(temp) + s(week) + s(time, k = 150) + dow,
family = nb,
data = chicago,
method = "REML"
)
summary(model_c)$s.table
c(deviance_explained = summary(model_c)$dev.expl)
AIC(model_a, model_b, model_c)
```
The AIC falls by `r f1(AIC(model_a) - AIC(model_b))` when the season enters, and by another `r f1(AIC(model_b) - AIC(model_c))` with the week before. What happens to the temperature curve?
```{r curve_function}
# 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"))
```
```{r temperature_curves}
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()
low_point <- sapply(split(three, three$model), function(d) d$temp[which.min(d$fit)])
low_point
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 `r low_point[[1]]` °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 `r f1(at_cold[[2]])`%, against `r f1(at_cold[[1]])`% 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:
```{r week_curve}
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()
```
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}$$
```{r combined}
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)
round(rbind(rr(-15), rr(-10), rr(0), rr(10), rr(28), rr(30)), 3)
```
```{r combined_chart}
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()
```
- The fewest people die at **`r answer$minimum` °C**, with an interval from `r answer$interval[[1]]` to `r answer$interval[[2]]` °C (from 2,000 simulated curves).
- At 30 °C the risk is `r f2(rr(30)$rr)` times as high, 95% CI [`r f2(rr(30)$low)`, `r f2(rr(30)$high)`]. At −15 °C, `r f2(rr(-15)$rr)` times, [`r f2(rr(-15)$low)`, `r f2(rr(-15)$high)`].
- 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:
```{r k_check}
k.check(model_c)
```
`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:
```{r larger_k}
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)
)
)
```
The minimum moves from `r answer$minimum` to `r answer_k$minimum` °C, and the AIC changes by `r f1(AIC(model_k) - AIC(model_c))`. 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
```{r acf}
lag1 <- sapply(list(A = model_a, B = model_b, C = model_c), function(m) {
acf(resid(m, type = "pearson"), plot = FALSE)$acf[2]
})
lag1
```
The residuals of neighboring days correlate at `r f2(lag1[["A"]])` in model A and `r f2(lag1[["C"]])` 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:
```{r season_sensitivity}
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)
```
The lowest point and the hot side do not depend on it. The cold side does: the relative risk at −15 °C goes from `r f2(season$RR_cold[1])` with a stiff season to `r f2(season$RR_cold[5])` 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:
```{r concurvity}
round(concurvity(model_c, full = FALSE)$estimate, 2)
```
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:
```{r heat_wave}
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))
c(minimum_without_it = answer_w$minimum)
```
The relative risk at 30 °C falls from `r f2(rr(30)$rr)` to `r f2(rr_w(30)$rr)`. 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 `r answer$minimum` to `r answer_w$minimum` °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:
```{r natural_spline}
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)]
```
With 4 degrees of freedom for each temperature and 7 per year for the season, the lowest point is at `r g$temp[which.min(p_ns)]` °C, against `r answer$minimum` °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:
```{r apa_numbers}
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* = `r num(nrow(chicago))` 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 `r paste(R.version$major, R.version$minor, sep = ".")`; R Core Team, `r R.version$year`) 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 `r f1(100 * summary(model_c)$dev.expl)`% of the deviance. The temperature with the lowest mortality was `r answer$minimum` °C, 95% CI [`r f1(answer$interval[[1]])`, `r f1(answer$interval[[2]])`]. Compared with it, the relative risk was `r f2(rr(-15)$rr)`, 95% CI [`r f2(rr(-15)$low)`, `r f2(rr(-15)$high)`], at −15 °C and `r f2(rr(30)$rr)`, 95% CI [`r f2(rr(30)$low)`, `r f2(rr(30)$high)`], at 30 °C (Table 2). Without the heat wave of 13–19 July 1995 the relative risk at 30 °C was `r f2(rr_w(30)$rr)`, 95% CI [`r f2(rr_w(30)$low)`, `r f2(rr_w(30)$high)`]. The lag-1 autocorrelation of the residuals was `r f2(lag1[["C"]])`.
**Table 1**
*Smooth Terms of the Model of Daily Deaths*
```{r apa_table, echo=FALSE}
knitr::kable(apa_table, col.names = c("Smooth", "Basis dimension", "edf", "χ²", "*p*"),
align = "lrrrr", format = "pipe", row.names = FALSE)
```
*Note.* *N* = `r num(nrow(chicago))` 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*
```{r apa_table2, echo=FALSE}
knitr::kable(data.frame(rr_table$t, f2(rr_table$rr), paste0("[", f2(rr_table$low), ", ", f2(rr_table$high), "]")),
col.names = c("Temperature (°C)", "Relative risk", "95% CI"), align = "rrr", format = "pipe", row.names = FALSE)
```
*Note.* Compared with `r answer$minimum` °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](EXAMPLE_LOESS.Rmd), [polynomial regression](EXAMPLE_POLYNOMIAL_REGRESSION.Rmd), [generalized linear models](EXAMPLE_GENERALIZED.rmd) |
---
## 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