library(ggplot2) # Visualization
library(tidyr) # Reshape data
library(dplyr) # Data manipulation
theme_set(theme_light())4. Linear regression in R
Packages
Airquality data
The airquality data contain daily measurements of air quality and weather in New York from 1 May to 30 September 1973 (Chambers et al., 1983). Ozone is the mean ozone concentration (ppb) between 13:00 and 15:00 on Roosevelt Island, measured by the New York State Department of Conservation. The weather variables come from the National Weather Service: Solar is the solar radiation (Langleys) in Central Park, Wind the average wind speed (mph), and Temp the daily maximum temperature (°F), both at LaGuardia Airport. Month, Day and Doy (day of year) give the date. In this lab, we model ozone as a function of temperature. In chapter multiple linear regression, we extend this model with further predictors.
airq <- read.table("data/airquality.txt", sep = ",", dec = ".", header = TRUE)
airq <- na.omit(airq) # remove observations with missing values
head(airq, 2) # print first two rows Doy Ozone Solar Wind Temp Month Day
1 121 41 190 7.4 67 5 1
2 122 36 118 8.0 72 5 2
ggplot(airq, aes(x = Temp, y = Ozone)) +
geom_point()
Ozone increases with temperature. Below about 75 °F, ozone concentrations are low and vary little. At higher temperatures, they rise more steeply and vary much more, with a few days above 100 ppb. The relationship is therefore not quite linear, and the spread of ozone grows with its level.
Variable transformations
A transformation of the response, the predictor, or both can help when the data do not meet the assumptions of a linear model. Transformations are used to:
- make a curved relationship linear,
- make the residual variance more constant,
- make skewed residuals more symmetric.
Common transformations are the logarithm for positive, right-skewed variables such as concentrations or biomass, and the square root for counts (Zuur et al., 2007, Sect. 4.2). The logarithm is only defined for positive values. If a variable contains zeros, a constant is sometimes added, as in log(y + 1), but the results then depend on the chosen constant. For responses with zeros, such as counts, generalized linear models are often a better choice than transforming the data.
In our example, ozone increases more steeply at high temperatures, and its spread grows with its level. We therefore add log-transformed ozone as a new column. Alternatively, transformations can be written directly into the model formula, as in lm(log(Ozone) ~ Temp).
airq$logOzone <- log(airq$Ozone)
ggplot(airq, aes(x = Temp, y = logOzone)) +
geom_point()
On the log scale, the relationship is closer to linear and the spread is more even. We therefore use log-transformed ozone as the response in this lab.
Fitting the model
A simple linear regression describes the response \(y\) as a straight-line function of a predictor \(x\) plus random error:
\[ y_i = \beta_0 + \beta_1 x_i + \epsilon_i, \qquad \epsilon_i \sim N(0, \sigma^2) \]
\(\beta_0\) is the intercept, \(\beta_1\) the slope, and \(\epsilon_i\) the deviation of observation \(i\) from the line. The errors are assumed to be independent and normally distributed with constant variance \(\sigma^2\). Least squares estimates \(\hat\beta_0\) and \(\hat\beta_1\) by minimizing the sum of squared differences between the observed values and the fitted line, called residuals. In our example, \(y\) is log ozone and \(x\) is temperature.
In R, the lm() function fits this model. It takes a formula of the form response ~ predictor, where the tilde (~) separates \(y\) from \(x\). The intercept, slope and error term are added automatically, so logOzone ~ Temp corresponds to \(\text{logOzone}_i = \beta_0 + \beta_1 \text{Temp}_i + \epsilon_i\).
lm_ozone <- lm(logOzone ~ Temp, data = airq) # fit model
lm_ozone # print the lm object
Call:
lm(formula = logOzone ~ Temp, data = airq)
Coefficients:
(Intercept) Temp
-1.84852 0.06767
lm() returns a model object containing the fitted model and information used for further analysis. Printing the object shows the model formula and estimated coefficients: the intercept and slope. We can add the fitted regression line to the scatterplot using geom_abline(), which draws a line from its intercept (\(\hat{\beta}_0\)) and slope (\(\hat{\beta}_1\)) as printed above:
ggplot(airq, aes(x = Temp, y = logOzone)) +
geom_point() +
geom_abline(intercept = -1.84852,
slope = 0.06767,
colour = "red")
Inference
Model summary
summary() gives a more detailed view of the fitted model:
summary(lm_ozone)
Call:
lm(formula = logOzone ~ Temp, data = airq)
Residuals:
Min 1Q Median 3Q Max
-2.14417 -0.32555 0.02066 0.34234 1.49100
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.848518 0.455080 -4.062 9.2e-05 ***
Temp 0.067673 0.005807 11.654 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.5804 on 109 degrees of freedom
Multiple R-squared: 0.5548, Adjusted R-squared: 0.5507
F-statistic: 135.8 on 1 and 109 DF, p-value: < 2.2e-16
The output starts with the model formula and a summary of the residuals, followed by the coefficient table and statistics for the model as a whole. We briefly go through the main parts here and look at them in more detail in the following sections.
Residuals: The minimum, quartiles, median and maximum of the residuals, the differences between observed and fitted values. For normally distributed errors, the median should be close to zero and the quartiles roughly symmetric around it. This holds here, but the minimum is further from zero than the maximum, which hints at individual observations far below the regression line. We examine the residuals more closely in the model diagnostics.
Coefficients: The estimates are the intercept (\(\hat\beta_0\), row
(Intercept)) and the slope (\(\hat\beta_1\), rowTemp). Their standard errors measure the uncertainty of the estimates and are the basis for confidence intervals. The t-tests check whether each coefficient differs from zero. Both do (p < 0.001), which for the slope is clear evidence that log ozone increases with temperature. Keep in mind that a p-value tells us only whether an effect differs from zero, not how large it is. Always interpret it together with the estimated effect and its confidence interval, the range of effect sizes compatible with the data and model assumptions (see interpreting coefficients).Residual standard error: In the model equation, the errors \(\epsilon_i\) scatter around the line with standard deviation \(\sigma\). The residual standard error is the estimate \(\hat\sigma\) of this standard deviation, calculated from the residuals (despite its name, it is not the standard error of an estimate). It tells us how far observations typically lie from the regression line, in units of the response (here log ozone). Its \(n - 2\) degrees of freedom reflect the two estimated coefficients.
\(R^2\): The coefficient of determination measures goodness of fit as the proportion of variation in the response explained by the model. It ranges from 0 (no variation explained) to 1 (all observations on the line). Temperature explains 55% of the variation in log ozone. \(R^2\) never decreases when predictors are added, even useless ones. The adjusted \(R^2\) corrects for the number of predictors and is used to compare models with different numbers of predictors in multiple linear regression.
F-test: Checks whether the model explains more variation than a model without predictors (see the ANOVA table). With a single predictor, it tests the same hypothesis as the t-test of the slope and gives the same p-value, so it becomes useful only with several predictors.
The t- and F-tests are only valid if the model assumptions hold. We check them in the model diagnostics below.
Extracting coefficients and model statistics
So far, we have used summary() to print the model results as text. To use individual results in further calculations, we extract them from the model object or from the summary object.
coef() returns the estimated intercept and slope. Use vector indexing to store them separately:
coef(lm_ozone)(Intercept) Temp
-1.84851790 0.06767266
intercept <- coef(lm_ozone)[1]
slope <- coef(lm_ozone)[2]The coefficient matrix of the summary adds the standard errors, t-values and p-values:
summary(lm_ozone)$coefficients Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.84851790 0.455080458 -4.061958 9.198430e-05
Temp 0.06767266 0.005806884 11.653868 7.167895e-21
Statistics of the whole model are extracted from the summary with the $ operator, for example \(R^2\), adjusted \(R^2\), and the F-statistic with its degrees of freedom:
summary(lm_ozone)$r.squared[1] 0.5547615
summary(lm_ozone)$adj.r.squared[1] 0.5506768
summary(lm_ozone)$fstatistic value numdf dendf
135.8126 1.0000 109.0000
Interpreting coefficients
In a linear regression, the intercept \(\beta_0\) is the predicted response at \(x = 0\), and the slope \(\beta_1\) is the change in the predicted response per unit increase in \(x\). In our example, log ozone increases by 0.068 per °F (95% CI: 0.056 to 0.079). The intercept is only meaningful if \(x = 0\) lies within or near the observed range of \(x\). Here, the intercept, -1.85, is the predicted log ozone at 0 °F, far below the observed temperatures of 57 to 97 °F, and therefore has no practical meaning. Centering the predictor, i.e. subtracting its mean, makes the intercept the predicted response at the mean temperature (see centered predictors).
The coefficients describe changes in log ozone, which are hard to interpret. To interpret them on the original scale, we back-transform the model:
\[ \log(y) = \beta_0 + \beta_1 x \quad\Leftrightarrow\quad y = e^{\beta_0} \cdot e^{\beta_1 x}, \]
so an increase in \(x\) by one unit multiplies \(y\) by \(e^{\beta_1}\). Effects are thus relative instead of absolute (Gelman et al., 2021, Sect. 12.4):
exp(coef(lm_ozone))(Intercept) Temp
0.1574704 1.0700150
Ozone increases by a factor of 1.07, or about 7%, per degree Fahrenheit. The back-transformed intercept, 0.16 ppb, is the predicted median ozone at 0 °F and, like the intercept itself, has no practical meaning here. The table summarizes the interpretation of \(\beta_1\) for the most common combinations:
| Model | Interpretation of \(\beta_1\) |
|---|---|
y ~ x |
\(y\) changes by \(\beta_1\) units per unit increase in \(x\) |
log(y) ~ x |
\(y\) changes by \(100 \cdot (e^{\beta_1} - 1)\)% per unit increase in \(x\) |
y ~ log(x) |
\(y\) changes by about \(\beta_1 / 100\) units per 1% increase in \(x\) |
log(y) ~ log(x) |
\(y\) changes by about \(\beta_1\)% per 1% increase in \(x\) |
Testing the model as a whole: ANOVA table and F-test
The F-test in the last line of the summary() output is derived from the analysis-of-variance (ANOVA) table, which compares how much variation the model explains with how much it leaves unexplained. The table partitions the total variation in the response (\(SSY\)) into the variation explained by the fitted regression (\(SSR\)) and the residual variation (\(SSE\)), which remains unexplained by the model.
\[ SSY = SSR + SSE \]
Here, \(SSY\) is the total sum of squares, measuring variation around the response mean; \(SSR\) is the regression sum of squares, measuring the variation explained by the fitted regression; and \(SSE\) is the error sum of squares, measuring the variation of the observed values around their fitted values.
The F-statistic compares the explained and unexplained variation, accounting for their respective degrees of freedom, where \(k\) is the number of predictors (\(k = 1\) in simple linear regression):
\[ F = \frac{SSR/k}{SSE/(n-k-1)}. \]
A large F-statistic indicates that the variation explained by the regression is large relative to the residual variation. In multiple linear regression, the F-test evaluates whether all slopes are jointly zero.
Calling anova() on a fitted lm() object produces an ANOVA table.
anova_ozone <- anova(lm_ozone)
anova_ozoneAnalysis of Variance Table
Response: logOzone
Df Sum Sq Mean Sq F value Pr(>F)
Temp 1 45.751 45.751 135.81 < 2.2e-16 ***
Residuals 109 36.719 0.337
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
In our example, the SSR is 45.75 and the SSE is 36.72. Substituting these values gives an F-statistic of:
\[ F = \frac{45.75 / 1} {36.72 / 109} \approx 135.81. \]
Under the null hypothesis that the slope is zero, this statistic follows an F-distribution with 1 and 109 degrees of freedom. The p-value is the upper-tail probability of observing an F-statistic at least this large, shown in the Pr(>F) column of the ANOVA table. A small p-value provides evidence that the slope differs from zero, indicating a statistically significant linear relationship.
Confidence and prediction intervals
Confidence intervals and bands
Confidence intervals quantify the uncertainty of the estimated coefficients and of the fitted line. confint() returns the 95% confidence intervals of the coefficients. Use level to change the confidence level:
confint(lm_ozone) 2.5 % 97.5 %
(Intercept) -2.7504726 -0.94656323
Temp 0.0561636 0.07918171
To obtain confidence intervals for the fitted line, we use predict(). As the name implies, predict() predicts the response at new predictor values, supplied with the newdata argument. Without newdata, it returns the fitted values for the observations. Setting interval = "confidence" adds their confidence intervals, which describe the uncertainty of the estimated mean response at each predictor value:
head(predict(lm_ozone, interval = "confidence")) fit lwr upr
1 2.685550 2.520169 2.850931
2 3.023914 2.895982 3.151845
3 3.159259 3.041671 3.276847
4 2.347187 2.135153 2.559221
7 2.550205 2.366904 2.733505
8 2.144169 1.901885 2.386453
The columns contain the fitted values (fit) and the lower (lwr) and upper (upr) interval limits. As with confint(), the default is a 95% interval, and level changes it.
Plotted as lines across all observations, the intervals form a confidence band:
pred_ozone <- lm_ozone |>
predict(interval = "confidence") |>
as.data.frame() |>
mutate(x = airq$Temp)
ggplot(airq, aes(x = Temp, y = logOzone)) +
geom_point() +
geom_line(data = pred_ozone, aes(x = x, y = fit)) +
geom_line(data = pred_ozone, aes(x = x, y = upr), linetype = "dashed") +
geom_line(data = pred_ozone, aes(x = x, y = lwr), linetype = "dashed")
The band describes the uncertainty of the fitted regression line, not the variability of individual observations. It is pointwise: the confidence level applies to the mean response at each predictor value separately, not to the entire line at once.
Prediction intervals and bands
Setting interval = "prediction" returns a prediction interval for an individual future response. It accounts for both uncertainty in the estimated mean response and the residual variation among individual observations, so it is wider than a confidence interval for the mean response.
pred_ozone <- lm_ozone |>
predict(interval = "prediction") |>
as.data.frame() |>
mutate(x = airq$Temp)Warning in predict.lm(lm_ozone, interval = "prediction"): predictions on current data refer to _future_ responses
ggplot(airq, aes(x = Temp, y = logOzone)) +
geom_point() +
geom_line(data = pred_ozone, aes(x = x, y = fit)) +
geom_line(data = pred_ozone, aes(x = x, y = upr), linetype = "dashed") +
geom_line(data = pred_ozone, aes(x = x, y = lwr), linetype = "dashed")
At a given \(x\), a 95% prediction interval is designed to contain the response of a new observation in approximately 95% of repeated samples, assuming the model is correctly specified. R’s warning makes the same point: we predicted at the observed temperatures, but the intervals refer to future observations at these temperatures, not to the observations already in the data.
Back-transforming predictions
The model describes log ozone, but interpretation is more meaningful on the original scale. Visualizing the fitted model with its prediction band requires back-transforming the predicted values. To draw a smooth curve, we need predictions at many evenly spaced temperatures, a so-called grid. A grid is a set of predictor values that we choose ourselves, independent of the observed temperatures, to cover the range of interest at regular intervals. seq() generates this grid from the lowest to the highest observed temperature in steps of 1 °F, so the curve stays within the range of the data. The grid is passed to predict() with newdata, a data frame whose column names must match the predictor names in the model formula. mutate(across(c(fit, lwr, upr), exp)) applies exp() to each of the three columns, which gives the predicted ozone and its prediction limits in ppb. The interval limits are percentiles of log ozone, and percentiles remain percentiles after back-transformation.
airq_new <- data.frame(Temp = seq(min(airq$Temp), max(airq$Temp), by = 1))
pred_ozone <- lm_ozone |>
predict(newdata = airq_new, interval = "prediction") |>
as.data.frame() |>
mutate(across(c(fit, lwr, upr), exp), x = airq_new$Temp)
head(pred_ozone) fit lwr upr x
1 7.454543 2.290546 24.26068 57
2 7.976473 2.456514 25.90017 58
3 8.534946 2.634221 27.65345 59
4 9.132520 2.824477 29.52863 60
5 9.771933 3.028142 31.53441 61
6 10.456115 3.246136 33.68014 62
Each row contains the predicted ozone and its prediction interval at one temperature. The plot combines two data frames: geom_point() uses the observations in airq, given in ggplot(), while each geom_line() takes pred_ozone through its own data argument. The solid line shows the fitted curve, the dashed lines the limits of the prediction band:
ggplot(airq, aes(x = Temp, y = Ozone)) +
geom_point() +
geom_line(data = pred_ozone, aes(x = x, y = fit), col = "red") +
geom_line(data = pred_ozone, aes(x = x, y = upr), col = "red", linetype = "dashed") +
geom_line(data = pred_ozone, aes(x = x, y = lwr), col = "red", linetype = "dashed")
On the original scale, the fitted line becomes a curve of the median ozone concentration. It rises more steeply at high temperatures and never predicts negative ozone. The prediction band widens with increasing ozone, as the spread of the data does.
Median vs. mean
The back-transformed values estimate the median ozone concentration at a given temperature, not the mean (Gelman et al., 2021, Sect. 3.5). The exponential function stretches positive residuals more than negative ones, so ozone is right-skewed on the original scale and its mean is higher than its median. exp() therefore underestimates the mean. Whether this matters depends on the question. The median describes a typical value, which is often sufficient. The mean is needed when predictions are summed or averaged, as in biomass or carbon inventories, where the correction is standard practice. To estimate the mean, multiply the back-transformed prediction \(\exp(\hat\mu)\), where \(\hat\mu\) is the fitted value on the log scale, by a correction factor greater than 1:
- If the residuals on the log scale are approximately normally distributed with variance \(\sigma^2\), the factor is \(\exp(\hat\sigma^2/2)\).
- Otherwise, use the smearing estimator (Duan, 1983), the average of the exponentiated residuals, \(\frac{1}{n}\sum_i \exp(e_i)\).
Model diagnostics
A fitted model and its summary statistics do not show whether a straight line describes the data well. The anscombe dataset, included with base R, makes this point. It contains four datasets with very similar summary statistics and the same fitted regression line, but very different relationships:
Only dataset 1 is well described by a straight line. Dataset 2 is curved, dataset 3 has a single outlier that pulls the line away from the other points, and in dataset 4 the slope is determined by a single observation. Always visualize the data and check the model before interpreting it.
Residuals
Most diagnostics are based on the residuals, the differences between the observed and fitted values, \(e_i = y_i - \hat{y}_i\). The fitted values \(\hat{y}_i\) are the responses predicted by the model at the observed predictor values.
Residual plots
Plotting residuals against fitted values helps reveal patterns that may indicate a misspecified mean relationship (e.g., a curve) or non-constant residual variance (e.g., a funnel shape), which makes standard errors and tests unreliable. Ideally, residuals should be scattered around zero without a clear pattern and with roughly constant vertical spread.
fitted() and residuals() extract the fitted values and residuals from the model object:
airq$fitted <- fitted(lm_ozone)
airq$residuals <- residuals(lm_ozone)
ggplot(data = airq, aes(x = fitted, y = residuals)) +
geom_point() +
geom_hline(yintercept = 0, col = "red")
The residuals are scattered around zero without a clear curve, so the straight line describes the log-transformed ozone well. Their spread is roughly constant, although it is somewhat smaller at the highest fitted values. A few days have large negative residuals, i.e. much less ozone than predicted. The largest is a day with only 1 ppb.
When the order of observations has meaning (for example, time or sampling sequence), plotting residuals in that order can reveal trends, cycles, or other dependence. The airquality data are daily measurements, so we plot the residuals against the day of the year (Doy):
ggplot(data = airq, aes(x = Doy, y = residuals)) +
geom_point() +
geom_hline(yintercept = 0, col = "red")
The residuals are not scattered randomly over the season. In May (day 121 to 151), most residuals are positive, so the model predicts less ozone than was measured. In June (day 152 to 181) and September (day 244 to 273), most are negative. Residuals of neighboring days are therefore more similar than residuals of days far apart.
Correlated residuals violate the assumption of independent errors. Neighboring days then partly repeat the same information, so the data contain less independent information than their sample size suggests. The standard errors of our model are therefore likely too small, and the confidence intervals and p-values above too optimistic. Part of the pattern may simply reflect a missing predictor: if something other than temperature changes over the season and affects ozone, our model cannot capture it. In chapter multiple linear regression, we test whether including the month improves the model. Correlation that remains requires models that account for it explicitly. It is common in environmental data, over time and in space, and you will learn how to handle spatial correlation in chapter spatial regression.
Normality of residuals
The linear model assumes normally distributed errors. If this assumption is violated, the t- and F-tests and the confidence and prediction intervals can be misleading. We check it with the residuals, starting with a histogram as a rough check:
ggplot(data = airq, aes(x = residuals)) +
geom_histogram()
Most residuals lie symmetrically around zero, but the left tail is longer: a few days have much less ozone than predicted.
Histograms are difficult to assess, especially with few data, because their shape depends on the bin width. A quantile-quantile plot (QQ plot) is easier to read. It compares each standardized residual with the value expected under a standard normal distribution. Standardized residuals are scaled to a mean of 0 and a standard deviation of 1, so they can be compared directly with the standard normal distribution. First, we sort the residuals. Then, for each residual, we:
- Determine its quantile, i.e., the proportion of residuals below it.
- Calculate the value of the standard normal distribution at the same quantile (
qnorm()). This is the residual expected under normality. - Plot the observed residual against the expected one.
If the residuals are normally distributed, observed and expected values agree and the points fall on the 1:1 line:
airq$resid_standard <- rstandard(lm_ozone) # standardized residuals
ggplot(airq, aes(sample = resid_standard)) +
stat_qq() +
geom_abline(intercept = 0, slope = 1)
Most points lie close to the line, but in the lower tail a few fall clearly below it: the largest negative residuals are more extreme than expected under normality. This matches the longer left tail in the histogram (Figure 6.4). The residuals are therefore slightly left-skewed, which suggests that the log transformation slightly overcorrects the right skew of ozone. For the analysis, this mild deviation probably has little consequence. With more than 100 observations, the t-tests and confidence intervals of the coefficients are robust to slight skewness. The prediction intervals depend more directly on normality and may be slightly less accurate in the lower tail. A stronger skew would call for a different transformation or a model with another error distribution, such as a generalized linear model.
Systematic departures from the line indicate deviations from normality. Points bending away from the line at one end indicate skewness, points departing at both ends in opposite directions indicate heavy or light tails, and single points far from the line indicate outliers. With small samples, some scatter around the line is expected, so use the QQ plot alongside other diagnostics. Try this demo to see how different deviations from normality appear in a QQ plot.
Functional relationship
Simple linear regression assumes that the mean response changes linearly with the predictor. This may not describe the data well. Inspect the scatterplot and compare plausible alternatives, such as transformed variables or a nonlinear model, when justified. Use subject-matter knowledge as well as statistical diagnostics when choosing a model.
A flexible smooth curve (method = "loess") follows the data without assuming a straight line. If it stays close to the fitted line, a linear relationship is adequate:
ggplot(airq, aes(x = Temp, y = logOzone)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", se = FALSE, col = "red", lwd = 0.5) +
geom_smooth(method = "loess", se = FALSE, col = "blue", lwd = 0.5)
The smooth curve stays close to the straight line over most of the temperature range. It flattens slightly above 90 °F, where there are only a few observations. A straight line is therefore an adequate description of log ozone.
Distribution of predictor
Linear regression makes no assumption about the distribution of the predictor. Still, the predictor values affect how well the relationship can be estimated:
- Extreme predictor values have high leverage (see below).
- Where observations are sparse, the fitted relationship is uncertain. Outside the observed range, predictions are extrapolations.
Therefore, check the range of the predictor and whether its values cover this range or include isolated extremes. When designing experiments or sampling surveys, cover the range of interest. If a few large values dominate, a transformation such as the logarithm can reduce their influence, but it changes the model and the interpretation of its coefficients.
ggplot(airq, aes(x = Temp)) +
geom_histogram(binwidth = 5)
Temperatures range from 57 to 97 °F, with most days between 70 and 90 °F. There are no isolated extreme values, so no single day dominates the fit. Few days are below 65 °F or above 90 °F, so the fit is less certain at both ends of the range.
Leverage, outliers, and influence
High-leverage observations have unusual predictor values and can strongly affect the fitted line. An outlier has a response value that is unusual relative to the model, usually reflected in a large residual. A point can have high leverage, be an outlier, both, or neither.
Influence describes how much a fitted model changes when an observation is removed. It depends on both leverage and the residual. Cook’s distance is a common measure of influence, which you can calculate with cooks.distance(). Values greater than 1 or greater than 4/(n − k − 1), where n is the number of observations and k the number of predictors, are sometimes used as flags for further investigation, not as automatic grounds for removing a point (Zuur et al., 2007, Sect. 5.1). With one predictor, the second threshold is 4/(n − 2).
airq$cooks <- cooks.distance(lm_ozone)
ggplot(airq, aes(x = Doy, y = cooks)) +
geom_point() +
geom_hline(yintercept = 4 / (nrow(airq) - 2), col = "red")
All values are well below 1. Six days exceed 4/(n − 2), but one stands out: 21 May, with only 1 ppb ozone at a low temperature (59 °F). It has the largest residual and, because few days are this cool, somewhat higher leverage than most days. Without it, the slope decreases from 0.068 to 0.063, so the conclusions do not change.
Do not remove an observation just because it is extreme. Exclusion needs a clear justification, such as a confirmed measurement error. You can also compare results with and without a flagged observation as a sensitivity analysis.
Diagnostics checklist
Regression diagnostics assess whether the model adequately describes the data and whether its assumptions are reasonable. In summary, check:
- Residuals for systematic patterns, dependence, and departures from normality when normal-theory inference is used.
- Whether the model adequately describes the functional relationship between response and predictor.
- The range and distribution of predictor values.
- High-leverage observations, response outliers, and influential points.
- Whether the variability around the fitted relationship is reasonably constant.
Summary
On the log scale, ozone increases almost linearly with temperature, by about 7% per °F, and temperature explains 55% of the variation in log ozone. The diagnostics support the straight line, and no single day dominates the fit. The residuals are slightly left-skewed, which probably matters little for the coefficients but may make the prediction intervals less accurate in the lower tail. More importantly, the residuals are correlated over the season, so the standard errors are likely too small, and ozone probably depends on more than temperature. In chapter multiple linear regression, we therefore add solar radiation, wind and month as predictors.