Regression analysis models the relationship between a continuous response variable and one or more predictor (explanatory) variables. In applied data science and statistics, regression serves two distinct purposes: inference (estimating how shifting a predictor relates to the expected outcome while holding other variables fixed) and prediction (generating accurate numerical forecasts for new observations).
In R, ordinary least squares (OLS) regression is built directly into base stats::lm(), supported by formula notation (y ~ x1 + x2), diagnostic plots (plot(fit)), confidence and prediction intervals (predict()), and regularized or non-linear extensions when standard OLS assumptions do not hold.
Simple and Multiple Linear Regression
A multiple linear regression model with $p$ predictors takes the form:
$$y_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \dots + \beta_p x_{ip} + \varepsilon_i, \qquad \varepsilon_i \sim \mathcal{N}(0, \sigma^2)$$
Ordinary least squares chooses coefficients $\hat{\beta}_0, \hat{\beta}_1, \dots, \hat{\beta}_p$ to minimize the residual sum of squares ($\text{RSS} = \sum_{i=1}^n (y_i – \hat{y}_i)^2$):
- Intercept ($\hat{\beta}_0$): Expected outcome when all numeric predictors equal
0and categorical predictors sit at their reference levels. Interpret with care if0lies outside the observed range of predictors. - Slope ($\hat{\beta}_j$): Expected change in $y$ for a one-unit increase in $x_j$, holding all other predictors in the model constant.
- Residuals ($e_i = y_i – \hat{y}_i$): Differences between observed values and fitted values; residual patterns reveal curvature, heteroscedasticity, or influential observations.
Fitting, Interpreting, and Predicting with lm() in R
Base R’s lm() fits linear models cleanly using formulas, factors, interaction terms, and predict() intervals:
R
set.seed(2026)
# Train / test split on built-in mtcars
idx <- sample(seq_len(nrow(mtcars)), size = floor(0.75 * nrow(mtcars)))
train_df <- mtcars[idx, ]
test_df <- mtcars[-idx, ]
# Fit multiple linear regression with factor and interaction terms
fit_lm <- lm(
mpg ~ wt + hp + factor(am) + wt:factor(am),
data = train_df
)
summary(fit_lm)
# Confidence interval for mean prediction vs. wider prediction interval for new rows
conf_int <- predict(fit_lm, newdata = test_df, interval = "confidence")
pred_int <- predict(fit_lm, newdata = test_df, interval = "prediction")
# Out-of-sample RMSE and MAE
test_preds <- pred_int[, "fit"]
rmse <- sqrt(mean((test_df$mpg - test_preds)^2))
mae <- mean(abs(test_df$mpg - test_preds))
c(RMSE = round(rmse, 3), MAE = round(mae, 3))
Notice the difference between interval = "confidence" and interval = "prediction": a confidence interval estimates uncertainty around the average response for a given predictor profile, whereas a prediction interval is wider because it also accounts for individual observation noise around the regression surface.
Core Assumptions and Model Diagnostics
Before trusting p-values, standard errors, or forecasts from an OLS model, inspect diagnostic checks across key modeling assumptions:
| Diagnostic / Assumption | What to Check in R | What Violations Look Like | Common Remedy |
| Linearity | Residuals vs. Fitted (plot(fit, which = 1)) | Curved or U-shaped trend in residuals | Add polynomial/spline terms or transform skewed predictors (log(), sqrt()) |
| Homoscedasticity | Scale-Location (plot(fit, which = 3)) | Residual spread widens or narrows with fitted values | Transform response/predictors or use heteroscedasticity-consistent SEs (sandwich::vcovHC()) |
| Normality of Errors | Normal Q-Q (plot(fit, which = 2)) | Heavy tails or skew deviating from the diagonal line | Inspect outliers/skewness; relevant mainly for small-sample inference |
| Leverage & Influence | Residuals vs. Leverage (plot(fit, which = 5)) / cooks.distance(fit) | Points with high Cook’s distance or extreme leverage | Audit data-entry errors, test sensitivity with and without influential rows |
| Multicollinearity | Variance Inflation Factors (car::vif(fit)) | High VIF values among correlated predictors | Drop/combine redundant features or use ridge/lasso regression (glmnet) |
Common Pitfalls and Extensions in R
Watch out for four frequent regression mistakes:
- Relying solely on in-sample $R^2$: Adding more predictors almost never decreases training $R^2$ (and can inflate it even with noise). Compare models using adjusted $R^2$, cross-validation, or held-out test RMSE/MAE.
- Ignoring data leakage during preprocessing: Standardizing predictors, imputing missing values, or selecting features on the full dataset before splitting into train and test sets leaks test information into training.
- Treating numeric codes as continuous scales: Ensure categorical variables stored as
0/1or integer codes are converted tofactorwhen they represent unordered groups. - Forcing linear OLS onto non-normal or bounded outcomes: For binary outcomes use logistic regression (
glm(..., family = binomial())), for event counts use Poisson or negative binomial regression, and for correlated or high-dimensional predictors consider regularized models (glmnet).
Practical Project Ideas for an R Portfolio
Strong regression projects in R pair clear domain interpretation with residual diagnostics and out-of-sample evaluation:
- Housing, Pricing, or Performance Regression Study: Build a multiple
lm()model on a real tabular dataset, test interactions or log transformations, inspect diagnostic plots and VIFs, and report out-of-sample RMSE and MAE. - Inference vs. Prediction Trade-Off Comparison: Fit both a clean explanatory linear model and a cross-validated or regularized regression model, comparing coefficient stability against predictive accuracy on held-out folds.
- Influential Points & Transformation Sensitivity Lab: Analyze a dataset with skewness or extreme observations in R, compare raw vs. transformed/robust specifications, and document how key estimates shift.