Linear regression is lm(y ~ x1 + x2, data). The formula notation is one of R's best ideas: ~ means "explained by", + adds a predictor, : is an interaction, * is both main effects and their interaction, . means every other column, and -1 removes the intercept.
Read summary() from the bottom up. The F-statistic says whether the model beats an intercept alone. Adjusted R-squared says how much variance it explains, penalised for predictor count - use the adjusted one, since plain R-squared can only rise as you add columns. Then the coefficients: each is the change in y per unit of that predictor with the others held constant, and that last clause is the part people drop when interpreting.
Diagnostics matter more than p-values, and plot(model) gives four in one call. Residuals vs Fitted should be a shapeless cloud - a curve means you have fitted a line to something bent; a funnel means non-constant variance. Q-Q should be roughly straight if residuals are normal. Scale-Location is the variance check again. Residuals vs Leverage finds points that are individually moving the fit, via Cook's distance. Multicollinearity - predictors explaining each other - inflates standard errors and makes coefficients unstable; car::vif() measures it, and above about 5 is worth acting on.
Logistic regression is for a binary outcome: glm(y ~ x, family = binomial). Its coefficients are log-odds, so exp(coef(model)) converts them to odds ratios, which is what you report.
tidymodels is the modern framework, and its value is that it makes the right workflow the easy one. Split before you look. Define preprocessing as a recipe that is fitted on the training set only - imputing with a median computed from all the data is data leakage, and it is why a model can score 0.95 in development and fail in production. Resample with cross-validation to tune, and touch the test set exactly once, at the end.
Choose the metric for the problem. Accuracy is misleading on imbalanced data - 99% accuracy on a 1-in-100 event is what you get by predicting "no" every time. ROC-AUC is threshold-independent; precision and recall tell you which kind of error you are making; the confusion matrix shows all four cells and should be looked at directly. For regression, RMSE is in the units of the outcome and punishes large errors; MAE is the average error and is more robust to outliers.
library(dplyr)
library(tidymodels)
# ---- Linear regression -----------------------------------------------
model <- lm(mpg ~ wt + hp, data = mtcars)
summary(model)
#
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 37.22727 1.59879 23.285 < 2e-16
# wt -3.87783 0.63273 -6.129 1.12e-06
# hp -0.03177 0.00903 -3.519 0.00145
#
# Adjusted R-squared: 0.8148 F-statistic: 69.21 on 2 and 29 DF
#
# wt = -3.88: one extra 1000 lb costs 3.88 mpg, WITH HORSEPOWER HELD
# CONSTANT. That clause is not optional - it is what the coefficient
# means, and dropping it is the commonest misreading of a regression.
confint(model) # the interval, which is the finding
coef(model)
# Formula notation:
# y ~ x1 + x2 two predictors
# y ~ x1 * x2 both, plus their interaction
# y ~ x1:x2 the interaction only
# y ~ . every other column
# y ~ x - 1 no intercept
# y ~ poly(x, 2) a quadratic term
# ---- Diagnostics: look at these before the p-values -----------------
par(mfrow = c(2, 2)); plot(model); par(mfrow = c(1, 1))
# 1 Residuals vs Fitted - want a shapeless cloud. A curve = wrong shape.
# 2 Q-Q Residuals - want roughly a straight line.
# 3 Scale-Location - want flat. A slope = non-constant variance.
# 4 Residuals vs Leverage- points outside Cook's lines move the fit.
# car::vif(model) # multicollinearity. Above ~5, act on it.
predict(model, newdata = data.frame(wt = 3, hp = 150),
interval = "prediction")
# ---- Logistic regression ---------------------------------------------
logit <- glm(am ~ wt + hp, data = mtcars, family = binomial)
summary(logit)
exp(coef(logit)) # log-odds -> ODDS RATIOS, which is what to report
predict(logit, type = "response") # probabilities, not log-odds
# ---- tidymodels: split, recipe, fit, evaluate ------------------------
set.seed(42) # reproducible splits
cars <- mtcars |> mutate(am = factor(am, labels = c("auto", "manual")))
# 1. SPLIT FIRST, before looking at anything.
split <- initial_split(cars, prop = 0.75, strata = am)
training_set <- training(split)
testing_set <- testing(split)
# 2. A recipe: preprocessing, fitted on the TRAINING data only.
rec <- recipe(am ~ wt + hp + disp, data = training_set) |>
step_impute_median(all_numeric_predictors()) |>
step_normalize(all_numeric_predictors()) |>
step_corr(all_numeric_predictors(), threshold = 0.9)
#
# Why a recipe rather than mutate(): every statistic here - the median,
# the mean and sd for normalising - is learned from the training set and
# APPLIED to the test set. Computing a median over all the data and then
# splitting is leakage, and it is why a model scores 0.95 in development
# and fails in production.
# 3. A model specification: what, and by which engine.
spec <- logistic_reg() |> set_engine("glm") |> set_mode("classification")
wf <- workflow() |> add_recipe(rec) |> add_model(spec)
# 4. Cross-validate on the training set to judge it before the test set.
folds <- vfold_cv(training_set, v = 5, strata = am)
res <- fit_resamples(wf, folds, metrics = metric_set(roc_auc, accuracy))
collect_metrics(res)
# 5. Fit on all the training data, and touch the test set ONCE.
final <- last_fit(wf, split, metrics = metric_set(roc_auc, accuracy))
collect_metrics(final)
preds <- collect_predictions(final)
conf_mat(preds, truth = am, estimate = .pred_class)
# Look at the matrix, not only the accuracy. 99% accuracy on a 1-in-100
# event is what "always predict no" scores.
# For regression the metrics change, not the workflow:
# metric_set(rmse, mae, rsq)
# rmse is in the outcome's units and punishes large errors
# mae is the average error, and is more robust to outliers
Discussion
No questions on this topic yet. Sign in to ask the first one.