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"))
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
Pairwise exploration
Question
Compare distributions of numeric variables with respect to categorical variable Insul
Covariance and correlation between Gas and Temp
Question
Compute the covariance matrix of Gas and Temp
Question
Build a scatterplot of the Whiteside dataset
Question
Build boxplots of Temp and Gas versus Insul
Question
Build violine plots of Temp and Gas versus Insul
Question
Plot density estimates of Temp and Gas versus Insul.
Hand-made calculation of simple linear regression estimates for Gas versus Temp
Question
Compute slope and intercept using elementary computations
Question
Overlay the scatterplot with the regression line.
Using lm()
lm stands for Linear Models. Function lm has a number of arguments, including:
formula
data
Question
Use lm() to compute slope and intercept
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
Question
Function glance() extract informations that can be helpful when performing model/variable selection.
Question
R offers a function confint() that can be fed with objects of class lm. Explain the output of this function.
Question
Plot a \(95\%\) confidence region for the parameters (assuming homoschedastic Gaussian noise).
Diagnostic plots
Method plot.lm() of generic S3 function plot from base R offers six diagnostic plots. By default it displays four of them.
Question
What are the diagnostic plots good for?
The diagnostic plots can be 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.
Recall that in the output of augment()
.fitted: \(\widehat{Y} = H \times Y= X \times \widehat{\beta}\)
.sigma: is meant to be the estimated standard deviation of components of \(\widehat{Y}\)
Compute the share of explained variance
Plot residuals against fitted values
Fitted against square root of standardized residuals.
TAF
Taking into account Insulation
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).
Check the design using function model.matrix(). How can you relate this augmented design and the one-hot encoding of variable Insul?
Function model.matrix() allows us to inspect the design matrix.
In order to solve le Least-Square problems, we have to compute \[(X^T \times X)^{-1} \times X^T\] This can be done in several ways.