Introduction
Linear regression in R is a straightforward way to model the relationship between a dependent variable and one or more independent variables, allowing you to make predictions, assess trends, and test hypotheses in fields ranging from economics to biology. This guide walks you through the entire process—from installing required packages to interpreting the output—so you can perform linear regression in R confidently and efficiently Worth knowing..
Steps
Load the required packages
- Install any missing packages with
install.packages("packageName"). - Load the packages using
library().- For basic functionality, the base R environment is sufficient.
- For advanced visualizations, load ggplot2 (ggplot2 is an R package for statistical graphics).
install.packages("ggplot2") # run once
library(ggplot2)
Prepare your data
- Import the dataset (e.g., CSV, Excel) using
read.csv()orreadxl::read_excel(). - Inspect the data with
head(),str(), andsummary()to ensure variables are numeric and correctly typed.
my_data <- read.csv("data.csv")
str(my_data) # check structure
summary(my_data) # view basic statistics
Fit the linear regression model
The core function is lm(), which creates a linear model object.
# Example: predict sales (y) from advertising spend (x)
model <- lm(sales ~ advertising, data = my_data)
- Formula syntax:
y ~ x1 + x2 + ...where~separates the dependent from independent variables. - Multiple predictors: simply add them with
+, e.g.,lm(y ~ x1 + x2 + x3, data = my_data).
Examine the model summary
The summary() method provides key statistics:
- Coefficients (estimates of the intercept and slopes) – bold values indicate significance.
- R-squared – proportion of variance explained by the model.
- p-values – test whether each coefficient differs significantly from zero.
summary(model)
Interpretation tips:
- A positive coefficient means an increase in the predictor leads to an increase in the outcome.
- The intercept represents the expected value of the dependent variable when all predictors are zero.
Check model assumptions
Linear regression relies on four main assumptions:
- Linearity – relationship between predictors and outcome is linear.
- Independence – observations are independent of each other.
- Homoscedasticity – constant variance of residuals across fitted values.
- Normality of residuals – residuals should be approximately normally distributed.
Diagnose assumptions with built-in plots
R’s plot() method for lm objects produces four diagnostic panels that address the assumptions directly:
par(mfrow = c(2, 2)) # arrange plots in a 2×2 grid
plot(model)
par(mfrow = c(1, 1)) # reset layout
What to look for in each panel:
| Plot | Assumption Checked | Ideal Pattern |
|---|---|---|
| Residuals vs Fitted | Linearity & Homoscedasticity | Random scatter around zero with no funnel shape or curved trend. Which means |
| Normal Q‑Q | Normality of residuals | Points fall on the diagonal line; systematic deviations at the tails suggest non-normality. |
| Scale‑Location (Spread‑Level) | Homoscedasticity | Horizontal band with roughly equal spread across fitted values. |
| Residuals vs apply | Influential observations | Points outside Cook’s distance contours (dashed red lines) may unduly influence coefficients. |
Supplement with formal tests
Visual inspection is essential, but statistical tests provide objective thresholds:
# 1. Normality – Shapiro-Wilk test on residuals
shapiro.test(residuals(model))
# 2. Homoscedasticity – Breusch-Pagan test (requires lmtest)
install.packages("lmtest")
library(lmtest)
bptest(model)
# 3. Autocorrelation (Independence) – Durbin-Watson test
dwtest(model)
# 4. Multicollinearity (for multiple regression) – VIF (requires car)
install.packages("car")
library(car)
vif(model) # values > 5–10 indicate problematic collinearity
Interpretation: A p-value < 0.05 in the Shapiro-Wilk or Breusch-Pagan tests signals a violation of normality or homoscedasticity, respectively. For Durbin-Watson, values near 2 suggest no autocorrelation Simple, but easy to overlook. That alone is useful..
Address common violations
| Violation | Typical Remedy |
|---|---|
| Non-linearity | Add polynomial terms (poly(x, 2)), splines (splines::ns()), or transform predictors (log(x), sqrt(x)). |
| Heteroscedasticity | Use dependable standard errors (sandwich::vcovHC() + lmtest::coeftest()), weighted least squares (lm(...Now, , weights = ... Day to day, )), or transform the response (Box-Cox via MASS::boxcox()). |
| Non-normal residuals | If sample size is large (> 30–50), the Central Limit Theorem often mitigates this; otherwise, try a response transformation or a generalized linear model (glm()). Think about it: |
| Influential points | Investigate outliers (data entry errors? Worth adding: ), then decide to keep, correct, or remove them. Consider solid regression (MASS::rlm()). |
Refine and compare models
When multiple predictors are available, use information criteria and cross-validation to avoid overfitting:
# Compare nested models with ANOVA (likelihood ratio test)
model_full <- lm(sales ~ advertising + price + season, data = my_data)
model_reduced <- lm(sales ~ advertising + price, data = my_data)
anova(model_reduced, model_full)
# Information criteria (lower is better)
AIC(model_full, model_reduced)
BIC(model_full, model_reduced)
# k-fold cross-validation (caret or tidymodels)
install.packages("caret")
library(caret)
train_control <- trainControl(method = "cv", number = 10)
cv_model <- train(sales ~ advertising + price, data = my_data,
method = "lm", trControl = train_control)
cv_model$results$RMSE # root-mean-square error on held-out folds
Make predictions with confidence
Once satisfied with the model, generate predictions for new data:
new_data <- data.frame(advertising = c(50, 75, 100),
price = c(20, 20, 20))
# Point predictions + 95% confidence intervals for the mean response
predict(model, newdata = new_data, interval = "confidence")
# Prediction intervals for individual future observations (wider)
predict(model, newdata = new_data, interval = "prediction")
Visualize the fitted relationship
A clear graphic communicates results more effectively than tables alone:
ggplot(my_data, aes(x = advertising, y = sales)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "lm", se = TRUE, color = "steelblue", fill = "lightblue") +
labs(title = "Sales vs. Advertising Spend",
subtitle = "Linear fit with 95% confidence band",
x = "Advertising Budget ($1000s)",
y = "Sales ($1000s)") +
theme_minimal()
For multiple predictors, consider partial regression plots (car::avPlots()
Extending the visual toolbox for richer models
When the explanatory set includes more than one predictor, a single‑axis scatter plot is no longer sufficient. Partial regression plots (avPlots) remain a useful starting point, but they can be complemented with a few additional graphics that reveal interaction effects and nonlinearity Took long enough..
- Interaction visualisation – Fit a model that contains an interaction term, for example
sales ~ advertising * price. Theinteractionspackage suppliesinteract_plot(), which produces a 2‑D surface that holds all other variables constant while varying the two interacting factors.
install.packages("interactions")
library(interactions)
interact_plot(lm(sales ~ advertising * price, data = my_data),
pred = advertising, modx = price,
plot.points = TRUE, interval = TRUE)
- Partial‑dependence plots – The
pdppackage creates averaged partial‑dependence plots that marginalise over the remaining predictors, making it easier to see the overall shape of the relationship.
install.packages("pdp")
library(pdp)
pdp::pdp(partial = ~ advertising + price,
plot.engine = "ggplot2",
data = my_data)
- Diagnostic heat‑maps – Multicollinearity can distort standard errors and obscure the true sign of coefficients. A quick variance‑inflation‑factor (VIF) table (
car::vif()) combined with a heat‑map of the correlation matrix (cor()) highlights regions where predictors overlap heavily.
install.packages("vif")
library(car)
vif(lm(sales ~ advertising + price + season, data = my_data))
cor_matrix <- cor(select(my_data, -sales))
corrplot::corrplot(cor_matrix, method = "color", order = "hclust")
Model finalisation and reporting
After the diagnostics and refinements are complete, the next step is to lock in the final specification and produce a clean, reproducible report. The broom package tidies the output, while stargazer (or gt for HTML) formats it for publication.
install.packages(c("broom", "stargazer"))
library(broom)
library(stargazer)
final_model <- lm(sales ~ advertising + price + season, data = my_data)
tidy(final_model) # coefficient estimates, SEs, p‑values
stargazer(final_model, type = "text",
title = "Final Linear Model of Sales",
dep.Day to day, var. labels = "Sales",
cov.
A concise narrative that accompanies the table should restate the purpose of each predictor, the direction of its effect, and any substantively important findings (e.But g. , a positive, statistically significant relationship between advertising spend and sales, or a diminishing return pattern captured by a quadratic term).
### Conclusion
Effective modelling of a continuous outcome begins with a clear understanding of the data‑generating process and proceeds through systematic diagnostics — checking for heteroscedasticity, non‑normality, influential observations, and multicollinearity. Transformations, solid techniques, and weighted least squares provide remedies when assumptions are violated. Which means once a parsimonious, well‑validated model is secured, predictions with confidence intervals, clear visualisations, and reproducible reporting round out the workflow. Consider this: model refinement is guided by information criteria, cross‑validation, and, when appropriate, stepwise or penalised approaches. By following these steps, analysts can move from a raw dataset to a trustworthy, interpretable model that delivers actionable insights.