The purpose of this lab is to introduce linear regression using base R and the tidyverse. We work on a dataset provided by the MASS package. This dataset is investigated in the book by Venables and Ripley. This discusssion is worth being read. Our aim is to relate regression as a tool for data exploration with regression as a method in statistical inference. To perform regression, we will rely on the base R function lm() and on the eponymous S3 class lm. We will spend time understanding how the formula argument can be used to construct a design matrix from a dataframe representing a dataset.
Packages installation and loading (again)
Code
# We will use the following packages. # If needed, install them : pak::pkg_install(). stopifnot(require("magrittr"),require("lobstr"),require("ggforce"),require("patchwork"), require("gt"),require("glue"),require("skimr"),require("corrr"),require("GGally"),require("broom"),require("tidyverse"),require("ggfortify"),require("autoplotly"))
Besides the tidyverse, we rely on skimr to perform univariate analysis, GGally::ggpairs to perform pairwise (bivariate) analysis. Package corrr provide graphical tools to explore correlation matrices. At some point, we will showcase the exposing pipe %$% and the classical pipe %>% of magrittr. We use gt to display handy tables, patchwork to compose graphical objects. glue provides a kind of formatted strings. Package broom proves very useful when milking lienar models produced by lm() (and many other objects produced by estimators, tests, …)
Dataset
The dataset is available from package MASS. MASS can be downloaded from cran.
Code
whiteside <- MASS::whiteside # no need to load the whole packagecur_dataset <-str_to_title(as.character(substitute(whiteside)))# ?whiteside
The documentation of R tells us a little bit more about this data set.
Mr Derek Whiteside of the UK Building Research Station recorded the weekly gas consumption and average external temperature at his own house in south-east England for two heating seasons, one of 26 weeks before, and one of 30 weeks after cavity-wall insulation was installed. The object of the exercise was to assess the effect of the insulation on gas consumption.
This means that our sample is made of 56 observations. Each observation corresponds to a week during heating season. For each observation. We have the average external temperature Temp (in degrees Celsius) and the weekly gas consumption Gas. We also have Insul which tells us whether the observation has been recorded Before or After treatment.
Temperature is the explanatory variable or the covariate. The target/response is the weekly Gas Consumption. We aim to predict or to explain the variations of weekly gas consumption as a function average weekly temperature.
The question is wether the treatment (insulation) modifies the relation between gas consumption and external temperature, and if we conclude that the treatment modifies the relation, in which way?.
Even though the experimenter, Mr Whiteside, decided to apply a treatment to his house. This is not exactly what we call experimental data. Namely, the experimenter has no way to clamp the external temperature. With respect to the Temperature variable (the explanatory variable) we are facing observational data.
Columnwise exploration
Question
Before before proceeding to linear regressions of Gas with respect to Temp, perform univariate analysis on each variable.
Compute summary statistics
Build the corresponding plots
Solution
skimr does the job. There are no missing data, complete rate is always 1, we remove non-informative columns from the output.
Both variables also pass the Jarque-Bera test with flying colors. This is noteworthy since the Jarque-Bera compares empirical skewness and kurtosis to Gaussian skewness and kurtosis.
Pairwise exploration
Question
Compare distributions of numeric variables with respect to categorical variable Insul
Solution
We start by plotting histograms
To abide to the DRY principle, we take advantage of the fact that aesthetics and labels can be tuned incrementally.
Code
p_xx <- whiteside |>ggplot() +geom_histogram(mapping=aes(fill=Insul, color=Insul, y=after_stat(density)),position="dodge",alpha=.1,bins=10) p_1 <- p_xx +aes(x=Temp) +theme(legend.position ="None")+labs(title="External Temperature",subtitle ="Weekly Average (Celsius)")p_2 <- p_xx +aes(x=Gas) +labs(title="Gas Consumption" ,subtitle="Weekly Average")# patchwork the two graphical objects (p_1 + p_2) + patchwork::plot_annotation(caption="Whiteside dataset from package MASS" )
Note the position parameter for geom_histogram(). Check the result for position="stack", position="identity". Make up your mind about the most convenient choice.
Gas Consumption distribution After looks shifted with respect to distribution Before.
Another visualization strategy consists in using the faceting mechanism
lm(Temp ~ Insul, data=whiteside) |>anova() |> broom::tidy() |> gt::gt() |> gt::fmt_number(decimals =3) |> gt::tab_caption("Testing temperature homogeneity over the seasons")
Testing temperature homogeneity over the seasons
term
df
sumsq
meansq
statistic
p.value
Insul
1.000
10.950
10.950
1.461
0.232
Residuals
54.000
404.855
7.497
NA
NA
The difference between temperature distributions over the two seasons is not deemed to be significant by ANOVA.
It is important that the grouping variable (here Insul) is a factor.
Covariance and correlation between Gas and Temp
Question
Compute the covariance matrix of Gas and Temp
Solution
Code
# Compute the covariance matrix for Gas and TempC <- whiteside |>select(where(is.numeric)) |>cov()mu_n <- whiteside %>%select(where(is.numeric)) %>%colMeans()
p <- whiteside |>ggplot() +aes(x=Temp, y=Gas) +geom_point(aes(shape=Insul)) +xlab("Average Weekly Temperature (Celsius)") +ylab("Average Weekly Gas Consumption 1000 cube feet") +labs(## Use list unpacking )p +ggtitle(glue("{cur_dataset} dataset"))
Note that the dataset looks like the stacking of two bananas corresponding to the two heating seasons.
In simple linear regression, the slope follows from the covariance matrix in a straightforward way. The slope can also be expressed as the linear correlation coefficient (Pearson) times the ration between the standard deviation of the response variable and the standard deviation of the explanatory variable.
lm stands for Linear Models. Function lm has a number of arguments, including:
formula
data
Question
Use lm() to compute slope and intercept. Denote the object created by constructor lm() as lm0.
What is the class of lm0 ?
Solution
Code
lm0 <-lm(Gas ~ Temp, data = whiteside)
The result is an object of class lm.
The generic function summary() has a method for class lm
Code
lm0 %>%summary()
Call:
lm(formula = Gas ~ Temp, data = whiteside)
Residuals:
Min 1Q Median 3Q Max
-1.6324 -0.7119 -0.2047 0.8187 1.5327
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 5.4862 0.2357 23.275 < 2e-16 ***
Temp -0.2902 0.0422 -6.876 6.55e-09 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.8606 on 54 degrees of freedom
Multiple R-squared: 0.4668, Adjusted R-squared: 0.457
F-statistic: 47.28 on 1 and 54 DF, p-value: 6.545e-09
The summary is made of four parts
The call. Very useful if we handle many different models (corresponding to different formulae, or different datasets)
A numerical summary of residuals
A commented display of the estimated coefficients
Estimate of noise scale (under Gaussian assumptions)
Squared linear correlation coefficient between response variable \(Y\) (Gas) and predictions \(\widehat{Y}\)
A test statistic (Fisher’s statistic) for assessing null hypothesis that slope is null, and corresponding \(p\)-value (under Gaussian assumptions).
Including a rough summary in a report is not always a good idea. It is easy to extract tabular versions of the summary using functions tidy() and glance() from package broom.
For html output gt::gt() allows us to polish the final output
Solution
We can use the exposing pipe from magrittr (or the with construct from base R) to build a function that extracts the coefficients estimates, standard error, \(t\)-statistic and associated p-values.
Code
tidy_lm <- . %$% ( # <1> The lhs is meant to be of class lmtidy(.) %>%# <2> . acts as a pronoun for magrittr pipes gt::gt() %>% gt::fmt_number(decimals=2) %>% gt::tab_caption(glue("Linear regrression. Dataset: {call$data}, Formula: {deparse(call$formula)}")) # <3> call is evaluated as a member of the pronoun `.`)tidy_lm(lm0)
Linear regrression. Dataset: whiteside, Formula: Gas ~ Temp
term
estimate
std.error
statistic
p.value
(Intercept)
5.49
0.24
23.28
0.00
Temp
−0.29
0.04
−6.88
0.00
deparse() is an important function from base R. It is very helpful when trying to take advantage of lazy evaluation mechanisms.
Question
Function glance() extract informations that can be helpful when performing model/variable selection.
Solution
The next chunk handles several other parts of the summary.
sigma estimates the noise standard deviation (under homoschedastic Gaussian noise assumption)
statistic is the Fisher statistic used to assess the hypothesis that the slope (Temp coefficient) is zero. It is compared with quantiles of Fisher distribution with 1 and 54 degrees of freedom (check pf(47.28, df1=1, df2=54, lower.tail=F) or qf(6.55e-09, df1=1, df2=54, lower.tail=F)).
Question
R offers a function confint() that can be fed with objects of class lm. Explain the output of this function.
Solution
Under the Gaussian homoschedastic noise assumption, confint() produces confidence intervals for estimated coefficients. Using the union bound, we can derive a conservative confidence rectangle.
Code
M <-confint(lm0, level=.95) as_tibble(M) |>mutate(Coeff=rownames(M)) |>relocate(Coeff) |> gt::gt() |> gt::fmt_number(decimals=2)
Plot a \(95\%\) confidence region for the parameters (assuming homoschedastic Gaussian noise).
Solution
Assuming homoschedastic Gaussian noise, the distribution of \((X^T X)^{1/2}\frac{\widehat{\theta}- \theta}{\widehat{\sigma}}\) is \(\frac{\mathcal{N}(0, \text{Id}_p)}{\sqrt{\chi^2_{n-p}/(n-p)}}\) with \(p=2\) and \(n=56\), where the Gaussian vector and the \(\chi^2\) variable are independent. Hence \[\frac{1}{2}\left\Vert (X^T X)^{1/2}\frac{\widehat{\theta}- \theta}{\widehat{\sigma}} \right\Vert^2= \frac{(\widehat{\theta}-\theta)^T X^TX (\widehat{\theta}-\theta)}{2\widehat{\sigma}^2}\] is distributed accordding to a Fisher distribution with \(p=2\) and \(n-p=54\) degrees of freedom. Let \(f_{\alpha}\) denote the quantile of order \(1-\alpha\) of the Fisher distribution with \(p=2\) and \(n-p=54\) degrees of freedom, the following ellipsoid is a \(1-\alpha\) confidence region: \[\left\{ \theta : \frac{(\widehat{\theta}-\theta)^T X^TX (\widehat{\theta}-\theta)}{2\widehat{\sigma}^2} \leq f_{\alpha}\right\}\]
Code
X <-model.matrix(lm0)coefficients(lm0)["(Intercept)"]
<ggproto object: Class CoordFixed, CoordCartesian, Coord, gg>
aspect: function
backtransform_range: function
clip: on
default: FALSE
distance: function
expand: TRUE
is_free: function
is_linear: function
labels: function
limits: list
modify_scales: function
range: function
ratio: 1
render_axis_h: function
render_axis_v: function
render_bg: function
render_fg: function
setup_data: function
setup_layout: function
setup_panel_guides: function
setup_panel_params: function
setup_params: function
train_panel_guides: function
transform: function
super: <ggproto object: Class CoordFixed, CoordCartesian, Coord, gg>
Diagnostic plots
Method plot.lm() of generic S3 function plot from base R offers six diagnostic plots. By default it displays four of them.
In order to obtain diagnostic plots as ggplot objects, use package ggfortify which defines an S3 method for class ‘lm’ for generic function autoplot (defined in package ggplot).
Question
What are the diagnostic plots good for?
Solution
Diagnostic plots for linear regression serve several purposes:
Visualization of possible dependencies between residuals and fitted values. OLS theory tells us that residuals and fitted values are (empirically) linearly uncorrelated. This does not preclude other kinds of dependencies.
With some overplotting, it is also possible to visualize possible dependencies between residuals and variables that were not taken into account while computing OLS estimates.
Assesment of possible heteroschedasticity, for example, dependence of noise variance on fitted values.
Assessing departure of noise distribution from Gaussian setting.
Spotting points with high leverage
Spotting possible outliers.
Question
Load package ggfortify, and call autoplot() (from ggplot2) to build the diagnostic plots for lm0.
Generic function autoplot() called on on an object of class lm builds a collection of grapical objects that parallel the output of base R generic plot() function. The graphical objects output by autoplot() can be further tweaked as any ggplot object.
Solution
Code
vanilla <-c("title"="Diagnostic plot for linear regression Gas ~ Temp","caption"="Whiteside data from package MASS")
Why points with high leverage and large standardized residuals matter.
The motivation and usage of diagnostic plots is explained in detail in the book by Fox and Weisberg: An R companion to applied regression.
In words, the diagnostic plots serve to assess the validity of the Gaussian linear modelling assumptions on the dataset. The assumptions can be challenged for a number of reasons:
The response variable may be a function of the covariates but not a lienar one.
The noise may be heteroschedastic
The noise may be non-Gaussian
The noise may exhibit dependencies.
The diagnostic plots are built from the information gathered in the lm object returned by lm(...).
It is convenient to extract the required pieces of information using method augment.lm. of generic functionaugment() from package broom.
(diag_1 + diag_2 + diag_3 +guide_area()) +plot_layout(guides="collect") +plot_annotation(title=glue("{cur_dataset} dataset"),subtitle =glue("Regression diagnostic {deparse(lm0$call$formula)}"), caption ='The fact that the sign of residuals depend on Insul shows that our modeling is too naive.\n The qqplot suggests that the residuals are not collected from Gaussian homoschedastic noise.' )
Taking into account Insulation
Question
Design a formula that allows us to take into account the possible impact of Insulation. Insulation may impact the relation between weekly Gas consumption and average external Temperature in two ways. Insulation may modify the Intercept, it may also modify the slope, that is the sensitivity of Gas consumption with respect to average external Temperature.
Have a look at formula documentation (?formula).
Solution
Code
lm1 <-lm(Gas ~ Temp * Insul, data = whiteside)vanilla_lm1 <- vanillavanilla_lm1["title"] <-"Diagnostic plot for linear regression Gas ~ Temp*Insul"
Question
Check the design using function model.matrix(). How can you relate this augmented design and the one-hot encoding of variable Insul?
InsulAfter is the result of one-hot encoding of boolean column Insul: Before is encoded by 0 and After is encoded by 1.
Temp:InsulAfter is the elementwise product of Temp and InsulAfter.
In one-hot-encoding, a categorical columns with k levels is mapped to k0-1 valued columns. An occurrence of level j : 1 ≤ j ≤ k is mapped to a sequence of j-10‘s, a 1, followed by k-j0’s.
The resulting matrix has column rank at most ’k-1’, since the rowsums are all equal to 1. In order to eliminate this redundancy, one of the k columns is dropped. Here the column with 1’s for Before has been dropped.
Note that other encodings (called contrasts in the statistics literature) are possible.
Question
Display and comment the part of the summary of lm1 concerning estimated coefficients.
Solution
Code
lm1 %>%tidy_lm()
Linear regrression. Dataset: whiteside, Formula: Gas ~ Temp * Insul
Comment the diagnostic plots built from the extended model using autoplot(). If possible, generate alternative diagnostic plots pipelining broom and ggplot2.
Solution
Code
diag_plots_lm1 <-autoplot(lm1, data=whiteside)
Code
diag_plots_lm1@plots[[1]] +labs(!!!vanilla_lm1,subtitle="Residuals versus fitted values" )
Try understanding the computation of .resid in an lm object. Compare .resid with the projection of Gas on the linear subspace orthogonal to the columns of the design matrix.
Solution
Code
sum((whiteside_aug1$.resid + H %*% whiteside_aug1$Gas - whiteside_aug1$Gas)^2)
[1] 3.461127e-28
Question
Understanding .hat
Solution
Code
sum((whiteside_aug1$.hat -diag(H))^2)
[1] 0
Question
Understanding .std.resid
Estimate noise intensity from residuals
Compare with the output of glance()
Solution
Code
sigma_hat <-sqrt(sum(lm1$residuals^2)/lm1$df.residual)lm1 |>glance() |> gt::gt() |> gt::fmt_number(decimals=2) |> gt::tab_caption(glue("The hand-made estimate of sigma is {round(sigma_hat,2)}"))
Column .sigma contains the leave-one-out estimates of \(\sigma\), that is whiteside_aug1$.sigma[i] is the estimate of \(\sigma\) you obtain by leaving out the i row of the dataframe.
There is no need to recompute everything for each sample element.
methods(autoplot) lists the S3 classes for which an autoplot method is defined. Some methods are defined in ggplot2, others like autoplot.lm are defined in extension packages like ggfortify.
S4 classes in R
The output of autoplot.lm is an instance of S4 class