Error in `annotate()`:
! Problem while setting up geom aesthetics.
ℹ Error occurred in the 8th layer.
Caused by error in `list_sizes()`:
! `x$label` must be a vector, not a call.
ℹ Read our FAQ about scalar types (`?vctrs::faq_error_scalar_type`) to learn more.
Statistical modeling : Linear regression
2025-07-07
Use cases for linear regression
Linear regression is particularly suited to a problem where the outcome of interest is on some sort of continuous scale (for example, quantity, money, height, weight). For outcomes of this type, it can be a first port of call before trying more complex modeling approaches. It is simple and easy to explain, and analysts will often accept a somewhat poorer fit using linear regression in order to avoid having to interpret a more complex model.
Here are some illustratory examples of questions that could be tackled with a linear regression approach:
Questions
- Linear regression is used to compare means?
- Linear regression has no assumptions involved? .
Why Linear Regression
Correlation and simple linear regression (LR) are used to investigate the relationship between two quantitative variables.
Correlation quantifies the strength and direction of a relationship between two variables, but it does not allow one to predict one variable from the other, while LR can be used to determine how the value of one variable varies in response to the values of the other variable.
Correlation does not specify a dependent or independent variable (symmetric relationship) but is just concerned with assessing the global movement shared between two variables, while LR specify one variable as the outcome and the other as the explanatory variable (asymmetric relationship)
Load required dataset
The mathematical equation of a straight line
Simple linear regression involves a numeric dependent (or outcome) variable \(Y\) and one independent (or explanatory) variable \(X\) that is either numeric or categorical.
The general equation of a straight line is: \[ Y_i = \beta_0 + \beta_1 X_i + \epsilon_i \tag{1}\]
Simple linear regression
Basic concepts
First, we plot the data in a scatter plot of the previous Plasma.volume vs Body weight dataset:
The objective is to find a mathematical approach that yields a line that, on average, goes through most of the points on the graph. This line is commonly known as a regression line or a line of best fit. We write the equation of the best-fitting line as:
\[\widehat{y_i} = b_0 + b_1 \cdot x_i\]
where \(b_0\) and \(b_1\) are best choices or estimates of the parameters \(\beta_0\) and \(\beta_1\) in Equation 1, and \(\hat y\) is the value of Y that is expected by this model for a specified value of X.
We define the following three concepts:
Observed value \(y_i\): the observed value of the dependent variable Y for a given \(x_i\) value.
Expected (or fitted) value \(\widehat{y_i}\): the value of the dependent variable Y that is expected by the model for a given \(x_i\) value.
Residual \(e_i\): the deviation (error) between the observed value \(y_i\) and the expected value \(\hat y\) for a given \(x_i\) value (\(e_i = y_i - \hat y_i\)).
Let’s see, for example, the values for the observation in the position 2 in our data set (?@fig-concepts).
The observed value \(y\) = 2.86 litres for \(x\) = 70 kg.
The expected value \(\widehat{y}\) is the value 3.14 litres on the regression line for \(x\) = 70. This value can be computed by the equation.
The residual is computed by subtracting the expected (fitted) value \(\widehat{y}\) from the observed value \(y\). In the case, it is \(y - \widehat{y} =\) - = litres.
Ordinary least squares (OLS) estimation of \(b_0\) and \(b_1\) in matrix form
Let’s describe for the \(i^{th}\) observation the underlying association between \(y_i\) and \(x_i\) by:
\[ Y_i = \beta_0 + \beta_1 X_i + \epsilon_i \]
- \(Y_i\): response (dependent) variable at i-th observation
- \(\beta_0,\beta_1\): regression parameters for intercept and slope.
- \(X_i\): known constant (independent or predictor variable) for i-th observation
- \(\epsilon_i\): random error term
\[ E(\epsilon_i) = 0 \\ \]
\[ var(\epsilon_i) = \sigma^2 \\ \]
\[ cov(\epsilon_i,\epsilon_j) = 0 \text{ for all } i \neq j \tag{2}\]
where the \(e_i\) is the error term, called residual, which represents the deviation between the observed value \(y_i\) and the expected value \(\hat y\) of the linear model (\(e_i = y_i - \hat y_i\)).
We make the following assumptions about \(e_i\)
LinearityThe relationship between the independent variable(s) and the outcome is linearZero Mean:The expected value of the error term is zeroHomoscedasticity:The error term has a constant varianceIndependence of Errors:There is no autocorrelation betweenNormality:The error terms are normally distributed
In a matrix notation, given \(n\) observations of the explanatory variable x and the outcome variable y, the Equation 2 becomes:
\[\begin{bmatrix} y_1\\ y_2 \\ y_3 \\ ... \\ y_n \end{bmatrix} = \begin{bmatrix} 1 & x_1\\ 1 & x_2\\ 1 & x_3\\ ... \\ 1 & x_n \end{bmatrix} \bullet \begin{bmatrix} b_0\\ b_1\end{bmatrix} + \begin{bmatrix} e_1\\ e_2 \\ e_3 \\ ... \\ e_n \end{bmatrix} \tag{3}\]
Then the outcome y can be compactly modeled by:
\[Y = X\hat{B} + e \tag{4}\]
where the matrix X is called the design matrix (the first column contains 1s, and the second column contains the actual observations of x).
The coefficients \(b_0\) and \(b_1\) are selected by minimizing the sum of squares of the residuals \(e\). It can be proven that the least squares estimates are obtained by the following matrix formula:
\[\hat{B} = (X^TX)^{-1}X^TY = \begin{bmatrix} b_0 \\ b_1 \end{bmatrix} \tag{5}\]
That is, we’ve got one matrix equation which gives us both coefficient estimates.
The is derived by the coefficient estimators by minimizing the sum of squared residuals \(SSE = (y - X \hat{\beta})' (y - X \hat{\beta})\). The result is
\[\hat{\beta} = (X'X)^{-1}X'y.\]
The residual standard error (RSE) estimates the sample deviation around the population regression line. (Think of each value of \(X\) along the regression line as a subpopulation with mean \(y_i\) and variance \(\sigma^2\). This variance is assumed to be the same for all \(X\).)
\[\hat{\sigma} = \sqrt{(n-k-1)^{-1} e'e}.\]
The standard error for the coefficient estimators is the square root of the error variance divided by \((X'X)\).
\[SE(\hat{\beta}) = \sqrt{\hat{\sigma}^2 (X'X)^{-1}}.\]
Run a simple regression model in R
- Fill in the gaps
Consider the following example
In R
Visualise the relationship graphically
Relationship between Age and Hb
Look at the coefficients
The summary() function shows \(\hat{\beta}\) as Estimate, \(SE({\hat{\beta}})\) as Std. Error, and \(\hat{\sigma}\) as Residual standard error. You can verify this by manually peforming these calculations using matrix algebra.
Here are the coefficient estimators, \(\hat{\beta} = (X'X)^{-1}X'y\).
Here is the residual standard error, \(\hat{\sigma} = \sqrt{(n-k-1)^{-1} \hat{e}'\hat{e}}\).
Use the residual standard errors to derive the standard errors of the coefficients, \(SE(\hat{\beta}) = \sqrt{\hat{\sigma}^2 (X'X)^{-1}}\).
Model Assumptions
The linear regression model assumes the relationship between the predictors and the response is linear with the residuals that are independent random variables normally distributed with mean zero and constant variance.
Additionally, you will want to check for multicollinearity in the predictors because it can produce unreliable coefficient estimates and predicted values.
Use a residuals vs fits plot \(\left( e \sim \hat{Y} \right)\) to detect non-linearity and unequal error variances, including outliers. The polynomial trend line should show that the residuals vary around \(e = 0\) in a straight line (linearity). The variance should be of constant width (especially no fan shape at the low or high ends).
Use a residuals normal probability plot to compares the theoretical percentiles of the normal distribution versus the observed sample percentiles. It should be approximately linear.
A scale-location plot \(\sqrt{e / sd(e)} \sim \hat{y}\) checks the homogeneity of variance of the residuals (homoscedasticity). The square root of the absolute value of the residuals should be spread equally along a horizontal line.
A residuals vs leverage plot identifies influential observations. A plot of the standardized residuals vs the leverage should fall within the 95% probability band.
Coefficient confidence
Intuitively, these coefficients appear too precise for comfort. After all, we are attempting to estimate a relationship based on a limited set of data. Like in any statistical estimation, the coefficients calculated for our model have a margin of error. Typically, in any such situation, we seek to know a 95% confidence interval to set a standard of certainty around the values we are interpreting.
The summary() function is a useful way to gather critical information in your model, including important statistics on your coefficients:
The 95% confidence interval corresponds to approximately two standard errors above or below the estimated value. For a given coefficient, if this confidence interval includes zero, you cannot reject the hypothesis that the variable has no relationship with the outcome. Another indicator of this is the Pr(>|t|) column of the coefficient summary, which represents the p-value of the null hypothesis that the input variable has no relationship with the outcome. If this value is less than a certain threshold (usually 0.05), you can conclude that this variable has a statistically significant relationship with the outcome. To see the precise confidence intervals for your model coefficients, you can use the confint() function.
Questions
Which of the following are true about Linear regression assumptions?
IdentifyOLS Reference
Penn State University, STAT 501, Lesson 12: Multicollinearity & Other Regression Pitfalls. https://newonlinecourses.science.psu.edu/stat501/lesson/12.
STHDA. Bootstrap Resampling Essentials in R. http://www.sthda.com/english/articles/38-regression-model-validation/156-bootstrap-resampling-essentials-in-r/
Molnar, Christoph. “Interpretable machine learning. A Guide for Making Black Box Models Explainable”, 2019. https://christophm.github.io/interpretable-ml-book/.