Linear regression

Programming and Data Analysis with R

Author
Affiliation

Tommaso Rigon

Università degli Studi di Milano-Bicocca

Homepage

Topics covered

  • Least squares (recap of Unit F) and the command lm
  • The simple linear regression model
  • Tests and confidence intervals for the slope
  • Confidence and prediction intervals
  • Diagnostic plots: residuals and normal Q-Q plot
  • Multiple linear regression: interpretation of the coefficients
NoteNote

The exercises associated with this unit are available at this link.

Back to Unit F

We have already met the simple linear regression in Unit F, with the forbes data: we predicted the atmospheric pressure from the boiling temperature of water. There, we computed:

  • the least squares estimates \hat{\alpha} and \hat{\beta};
  • the predicted values, for instance the pressure when water boils at 97 degrees Celsius;
  • the coefficient R^2, to measure the goodness of fit.

That analysis was purely descriptive: it only concerned the n = 17 observed locations. In this unit, we make inference, using the tools of Unit I and Unit J: standard errors, tests and confidence intervals.

Black cherry trees

For n = 31 black cherry trees in the Allegheny National Forest (Pennsylvania, USA), the data report:

  • the diameter of the trunk, measured at about 1.37 m above the ground;
  • the height of the tree;
  • the volume of timber obtained from the tree, after felling it.

The diameter is easy to measure on a standing tree. The volume, instead, is known only after the tree has been cut down.

NoteResearch question

Can we predict the volume of timber of a tree from its diameter, before cutting it down? How precise is the prediction?

Importing the trees data

As done previously, first of all you need to download the file trees.csv and save it on your computer. Link to the file

trees <- read.table("data/trees.csv", header = TRUE, sep = ",")

Alternatively, we can simply obtain them using the link:

path <- "https://tommasorigon.github.io/EnvEcoStat/data/trees.csv"
trees <- read.table(path, header = TRUE, sep = ",")
str(trees)
'data.frame':   31 obs. of  3 variables:
 $ Girth : num  8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
 $ Height: int  70 65 63 72 81 83 66 75 80 75 ...
 $ Volume: num  10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...

The variable Girth is, despite its name, the diameter of the trunk.

Preliminary operations

The original measurements are in inches, feet and cubic feet. We convert them into centimetres, metres and cubic metres, recalling that 1 inch = 2.54 cm, 1 foot = 0.3048 m and 1 cubic foot = 0.0283 m^3.

cherry <- data.frame(
  diameter = round(trees$Girth * 2.54, 1), # cm
  height = round(trees$Height * 0.3048, 1), # m
  volume = round(trees$Volume * 0.0283168, 3) # cubic metres
)
summary(cherry)
    diameter         height          volume      
 Min.   :21.10   Min.   :19.20   Min.   :0.2890  
 1st Qu.:28.05   1st Qu.:21.90   1st Qu.:0.5495  
 Median :32.80   Median :23.20   Median :0.6850  
 Mean   :33.65   Mean   :23.17   Mean   :0.8544  
 3rd Qu.:38.70   3rd Qu.:24.40   3rd Qu.:1.0565  
 Max.   :52.30   Max.   :26.50   Max.   :2.1800  

The height will be used later in this unit.

The scatterplot

plot(cherry$diameter, cherry$volume,
  pch = 16,
  xlab = "Diameter (cm)", ylab = "Volume (cubic metres)"
)

cor(cherry$diameter, cherry$volume)
[1] 0.9670996

The relationship is strong and approximately linear.

The least squares line

In Unit F, as in the course of Statistics, we denoted the intercept and the slope by \alpha and \beta. From now on, as in the theory lectures, we denote them by \beta_0 and \beta_1. In a linear model of the form y_i = \beta_0 + \beta_1 x_i + \epsilon_i, the least squares estimates are equal to \hat{\beta}_0 = \bar{y} - \hat{\beta}_1\:\bar{x}, \qquad \hat{\beta}_1 = \frac{\text{cov}(x,y)}{\text{var}(x)}.

We use again the functions my_var and my_cov of Unit F:

my_var <- function(x) mean(x^2) - mean(x)^2
my_cov <- function(x, y) mean(x * y) - mean(x) * mean(y)

x <- cherry$diameter
y <- cherry$volume
beta1_hat <- my_cov(x, y) / my_var(x) # Slope
beta0_hat <- mean(y) - beta1_hat * mean(x) # Intercept
c(beta0_hat, beta1_hat)
[1] -1.04665563  0.05648646

Each additional centimetre of diameter corresponds, on average, to 0.056 m^3 of additional timber.

The command lm

In Unit F we mentioned that the command lm (linear model) computes the same estimates. The formula volume ~ diameter reads “volume as a function of diameter”:

fit <- lm(volume ~ diameter, data = cherry)
coef(fit) # Least squares estimates
(Intercept)    diameter 
-1.04665563  0.05648646 

The object fit contains much more. For instance, the fitted values \hat{\mu}_i = \hat{\beta}_0 + \hat{\beta}_1x_i and the residuals e_i = y_i - \hat{\mu}_i:

head(fitted(fit))
        1         2         3         4         5         6 
0.1452087 0.1847492 0.2186411 0.4615329 0.4897761 0.5010734 
head(residuals(fit))
          1           2           3           4           5           6 
0.146791308 0.107250786 0.070358909 0.002467128 0.042223897 0.056926605 

As in Unit F, the coefficient R^2 can be obtained in two different ways: R^2 = 1 - \frac{\text{var}(e)}{\text{var}(y)} = \text{cor}(x,y)^2.

e <- residuals(fit)
1 - my_var(e) / my_var(y)
[1] 0.9352816
cor(x, y)^2
[1] 0.9352816
plot(cherry$diameter, cherry$volume,
  pch = 16,
  xlab = "Diameter (cm)", ylab = "Volume (cubic metres)"
)
abline(fit) # Same as abline(a = beta0_hat, b = beta1_hat)

Why exactly this line? Among all the lines \beta_0 + \beta_1 x, the least squares line is the one with the smallest sum of squared residuals \sum_{i=1}^n e_i^2, as the following video shows.

The linear regression model

So far, as in Unit F, we have only described the 31 trees. But these trees are a sample: we are interested in the relationship between diameter and volume for all the black cherry trees of the forest.

The simple linear regression model assumes that Y_i = \beta_0 + \beta_1 x_i + \epsilon_i, \qquad i = 1,\dots,n, where the errors \epsilon_1,\dots,\epsilon_n are independent, with distribution \text{N}(0, \sigma^2). The values x_1,\dots,x_n of the diameter are treated as fixed, non-random, numbers: only the errors \epsilon_i, and therefore the volumes Y_i, are random. As in Unit I, capital letters denote random variables. Therefore:

  • \beta_0 and \beta_1 are parameters, and \hat{\beta}_0 and \hat{\beta}_1 are their estimates;
  • \beta_0 + \beta_1 x is the mean volume of the trees with diameter x;
  • \sigma measures how much the volumes vary around this mean.

The variance \sigma^2 is estimated by s^2 = \frac{1}{n - 2}\sum_{i=1}^n e_i^2, where we divide by n - 2 because two parameters, \beta_0 and \beta_1, have been estimated.

n <- nrow(cherry)
s <- sqrt(sum(e^2) / (n - 2))
s
[1] 0.1204156
sigma(fit) # The same value, computed by R
[1] 0.1204156

Note that s is not the standard deviation of the volumes, computed by sd(y): it measures how much the volumes vary around the line.

The standard error of \hat{\beta}_1

Under the model, as for \bar{Y} in Unit I, we have that \mathbb{E}[\hat{\beta}_1] = \beta_1, \qquad \sigma_{\hat{\beta}_1} = \frac{\sigma}{\sqrt{\sum_{i=1}^n (x_i - \bar{x})^2}}. The estimator \hat{\beta}_1 is therefore unbiased, and its standard error decreases with n. Replacing \sigma with s, we obtain the estimated standard error, denoted by \text{s.e.}(\hat{\beta}_1) in the theory lectures:

se_hat <- s / sqrt(sum((x - mean(x))^2)) # Estimated standard error
se_hat
[1] 0.00275923

As for the mean in Unit J, we have that T = \frac{\hat{\beta}_1 - \beta_1}{S/\sqrt{\sum_{i=1}^n (x_i - \bar{x})^2}} \sim t_{n-2}. Hence, the tests and the confidence intervals for \beta_1 follow the same recipe of Unit J, with n - 2 degrees of freedom instead of n - 1.

A test for the slope

Is the diameter related to the volume? If \beta_1 = 0, the mean volume does not depend on the diameter. We test H_0: \beta_1 = 0 against H_a: \beta_1 \neq 0. Under H_0, the test statistic t = \frac{\hat{\beta}_1 - 0}{s/\sqrt{\sum_{i=1}^n (x_i - \bar{x})^2}} has a t distribution with n - 2 degrees of freedom.

t_obs <- (beta1_hat - 0) / se_hat # Observed test statistic
t_obs
[1] 20.47182
qt(0.975, df = n - 2) # Critical value, significance level 5%
[1] 2.04523
2 * (1 - pt(abs(t_obs), df = n - 2)) # Two-sided P-value
[1] 0

The observed statistic falls in the critical region, |t| > 2.05, and the P-value is practically zero: we reject H_0. Not a surprise, looking at the scatterplot.

The command summary

All these quantities are reported by the command summary:

summary(fit)

Call:
lm(formula = volume ~ diameter, data = cherry)

Residuals:
      Min        1Q    Median        3Q       Max 
-0.231019 -0.086952  0.003548  0.100494  0.272414 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -1.046656   0.095347  -10.98 7.64e-12 ***
diameter     0.056486   0.002759   20.47  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1204 on 29 degrees of freedom
Multiple R-squared:  0.9353,    Adjusted R-squared:  0.933 
F-statistic: 419.1 on 1 and 29 DF,  p-value: < 2.2e-16

In the table Coefficients, for each parameter:

  • Estimate is the estimate, \hat{\beta}_0 or \hat{\beta}_1;
  • Std. Error is its estimated standard error;
  • t value is the test statistic for H_0: \beta_0 = 0 or H_0: \beta_1 = 0;
  • Pr(>|t|) is the two-sided P-value.

Moreover, Residual standard error is s, with its n - 2 = 29 degrees of freedom, and Multiple R-squared is R^2. The last line will be discussed later in this unit.

A confidence interval for the slope

As in Unit J, a 95\% confidence interval for \beta_1 is \left(\hat{\beta}_1 - t_{0.975,\,n-2} \frac{s}{\sqrt{\sum_{i=1}^n (x_i - \bar{x})^2}}, \ \hat{\beta}_1 + t_{0.975,\,n-2} \frac{s}{\sqrt{\sum_{i=1}^n (x_i - \bar{x})^2}}\right).

t_quant <- qt(0.975, df = n - 2) # Quantile of order 0.975
c(beta1_hat - t_quant * se_hat, beta1_hat + t_quant * se_hat)
[1] 0.05084320 0.06212972
confint(fit) # Both beta_0 and beta_1, 95% by default
                 2.5 %      97.5 %
(Intercept) -1.2416615 -0.85164981
diameter     0.0508432  0.06212972

With 95\% confidence, each additional centimetre of diameter corresponds to between 0.051 and 0.062 m^3 of additional timber, on average.

Prediction

A forester measures a standing tree with a diameter of 40 cm. As in Unit F, the predicted volume is \hat{\beta}_0 + \hat{\beta}_1 \cdot 40. The command predict gives the same value, and requires a data frame with the new values of the explanatory variable:

beta0_hat + beta1_hat * 40
[1] 1.212803
new_tree <- data.frame(diameter = 40)
predict(fit, newdata = new_tree)
       1 
1.212803 

How precise is this prediction? There are two different questions:

  • what is the mean volume of all the trees with diameter 40 cm? This is the parameter \beta_0 + \beta_1 \cdot 40, and we need a confidence interval;
  • what is the volume of this particular tree? This is a random variable, and we need a prediction interval.
predict(fit, newdata = new_tree, interval = "confidence")
       fit      lwr      upr
1 1.212803 1.155893 1.269712
predict(fit, newdata = new_tree, interval = "prediction")
       fit       lwr     upr
1 1.212803 0.9600355 1.46557

The prediction interval is much wider: besides the uncertainty about \beta_0 and \beta_1, it also accounts for the variability \sigma of the single trees around the mean.

Residual plots

The normal linear model relies on four assumptions, summarised in the theory lectures by the acronym L.I.N.E.: Linearity, Independence, Normality and Equal variance of the errors. Independence depends on how the data were collected; the other three are checked through the residuals. First, we plot the residuals e_i against the fitted values \hat{\mu}_i:

plot(fitted(fit), residuals(fit),
  pch = 16,
  xlab = "Fitted values", ylab = "Residuals"
)
abline(h = 0, lty = "dashed") # Horizontal line at zero

If the model were adequate, we would see a cloud without patterns around zero. Here, instead, the residuals are positive at the two extremes and negative in the middle: the relationship is curved.

A fan-shaped cloud, with residuals more and more spread out as the fitted values increase, would instead indicate that the variance is not constant.

Diagnostic plots

The tests and the intervals also assume normal errors; this matters especially for the prediction intervals. The command plot, applied to the output of lm, draws several diagnostic plots. We consider the first two:

par(mfrow = c(1, 2)) # Two plots side by side
plot(fit, which = 1:2)

par(mfrow = c(1, 1))
  • Residuals vs Fitted is the plot of the previous section. The red line follows the average trend of the residuals: it should be roughly flat around zero, while here it is U-shaped. R also labels the three observations with the largest residuals: number 31 is the largest tree.
  • Q-Q Residuals (normal Q-Q plot) compares the ordered standardised residuals, that is the residuals divided by their estimated standard deviation, with the quantiles of a standard normal distribution. If the errors are normal, the points lie close to the dotted line. Here they do, apart from small departures at the two extremes: the normality assumption is reasonable.

Extrapolation

Besides the curvature, there is a second problem. For a small tree, the predicted volume is negative:

predict(fit, newdata = data.frame(diameter = 15))
         1 
-0.1993587 

The smallest tree in the data has a diameter of 21.1 cm: predicting outside the range of the observed data (extrapolation) is dangerous.

Adding the height

The volume of a tree does not depend on its diameter only: taller trees have, on average, more timber.

NoteResearch question

Does the height of a tree help to predict its volume, once the diameter is known?

Scatterplot matrix

With three variables, the command pairs draws all the scatterplots at once, and cor applied to the data frame returns all the correlations:

pairs(cherry, pch = 16)

round(cor(cherry), 2)
         diameter height volume
diameter     1.00   0.52   0.97
height       0.52   1.00   0.60
volume       0.97   0.60   1.00

The volume is strongly related to the diameter and, less strongly, to the height. Note also that the two explanatory variables are related to each other: taller trees tend to have a larger diameter.

The multiple linear regression model

The multiple linear regression model with two explanatory variables assumes that Y_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \epsilon_i, \qquad i = 1,\dots,n, where x_{i1} is the diameter and x_{i2} the height of the ith tree. As in the simple model, the values x_{i1} and x_{i2} are treated as fixed, and the errors \epsilon_1,\dots,\epsilon_n are independent, with distribution \text{N}(0, \sigma^2). Therefore:

  • \beta_0 + \beta_1 x_1 + \beta_2 x_2 is the mean volume of the trees with diameter x_1 and height x_2;
  • \beta_1 is the change in the mean volume when the diameter increases by 1 cm, at fixed height;
  • \beta_2 is the change in the mean volume when the height increases by 1 m, at fixed diameter.

The estimates \hat{\beta}_0, \hat{\beta}_1 and \hat{\beta}_2 are again obtained by least squares, that is by minimising \sum_{i=1}^n (y_i - \beta_0 - \beta_1 x_{i1} - \beta_2 x_{i2})^2. There is no simple formula as in Unit F: we let R do the computations.

Fitting the model with two variables

The explanatory variables are listed in the formula, separated by +:

fit2 <- lm(volume ~ diameter + height, data = cherry)
coef(fit2)
(Intercept)    diameter      height 
-1.63410974  0.05254189  0.03108235 

For two trees with the same height, one additional centimetre of diameter corresponds, on average, to 0.053 m^3 of additional timber. For two trees with the same diameter, one additional metre of height corresponds, on average, to 0.031 m^3 of additional timber. In short, we say that these are the effects of the diameter and of the height, each adjusting for the other variable.

The output of summary

summary(fit2)

Call:
lm(formula = volume ~ diameter + height, data = cherry)

Residuals:
      Min        1Q    Median        3Q       Max 
-0.180164 -0.074464 -0.005866  0.062388  0.242487 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) -1.634110   0.244261  -6.690 2.92e-07 ***
diameter     0.052542   0.002953  17.790  < 2e-16 ***
height       0.031082   0.012071   2.575   0.0156 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1102 on 28 degrees of freedom
Multiple R-squared:  0.9477,    Adjusted R-squared:  0.9439 
F-statistic: 253.5 on 2 and 28 DF,  p-value: < 2.2e-16

The output is read as for the simple model, with a few differences:

  • in the table Coefficients, the rows diameter and height test H_0: \beta_1 = 0 and H_0: \beta_2 = 0, that is, whether each variable is useful given the other one. The test statistics are computed as for the simple model, estimate divided by standard error, but now have a t distribution with n - 3 degrees of freedom. The height has a P-value of 0.016: it helps to predict the volume, even when the diameter is known;
  • the variance \sigma^2 is estimated by s^2 = \frac{1}{n - 3}\sum_{i=1}^n e_i^2, because three parameters have been estimated: Residual standard error is s, with n - 3 = 28 degrees of freedom;
  • the last line is the F test of H_0: \beta_1 = \beta_2 = 0, that is, whether at least one of the variables is useful. Here the P-value is practically zero.

The coefficient R^2 increases from 0.935 (diameter only) to 0.948. It is still defined as R^2 = 1 - \text{var}(e)/\text{var}(y), but it is no longer the square of the correlation between y and a single explanatory variable.

Confidence intervals

As for the simple model, the 95\% confidence intervals are obtained with confint:

confint(fit2)
                   2.5 %      97.5 %
(Intercept) -2.134456110 -1.13376336
diameter     0.046492187  0.05859159
height       0.006355497  0.05580920

Prediction with two variables

Two standing trees have the same diameter, 40 cm, but different heights, 20 m and 25 m. The data frame given to predict must now contain both variables:

new_trees <- data.frame(diameter = c(40, 40), height = c(20, 25))
predict(fit2, newdata = new_trees, interval = "prediction")
       fit       lwr      upr
1 1.089213 0.8375444 1.340881
2 1.244624 1.0115770 1.477672

The taller tree is expected to have about 0.16 m^3 of additional timber. As before, interval = "confidence" would instead give the intervals for the mean volume.

Diagnostic plots, again

par(mfrow = c(1, 2))
plot(fit2, which = 1:2)

par(mfrow = c(1, 1))

The residuals show the same curvature seen in the simple model: adding the height improves the predictions, but it does not fix this problem. The normal Q-Q plot, instead, does not show strong departures from normality. The model is useful, but it is only an approximation.