2025-10-21
Predicting miles-per-gallon (mpg) from car weight (wt) using mtcars.
ggplot2.plotly.The simple linear regression model:
\[ Y_i = \beta_0 + \beta_1 X_i + \varepsilon_i,\quad \varepsilon_i\overset{iid}{\sim}N(0,\sigma^2) \]
Assumptions: linearity, independence, homoscedasticity, normal errors.
Ordinary Least Squares estimates:
\[ \hat{\beta}_1 = \frac{\sum_i (X_i-\bar X)(Y_i-\bar Y)}{\sum_i (X_i-\bar X)^2},\qquad \hat{\beta}_0 = \bar Y - \hat{\beta}_1\bar X. \]
Standard error of \(\hat{\beta}_1\):
\[ \mathrm{Var}(\hat{\beta}_1) = \frac{\sigma^2}{\sum_i (X_i-\bar X)^2} \quad\text{and}\quad \hat\sigma^2 = \frac{1}{n-2}\sum_i \hat\varepsilon_i^2. \]
data(mtcars) knitr::kable(head(mtcars, 8))
| mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |
| Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
| Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |
| Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
| Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |
| Valiant | 18.1 | 6 | 225.0 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 |
| Duster 360 | 14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 |
| Merc 240D | 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 |
# Fit the simple linear regression model <- lm(mpg ~ wt, data = mtcars) summary(model)
## ## Call: ## lm(formula = mpg ~ wt, data = mtcars) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.5432 -2.3647 -0.1252 1.4096 6.8727 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 37.2851 1.8776 19.858 < 2e-16 *** ## wt -5.3445 0.5591 -9.559 1.29e-10 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 3.046 on 30 degrees of freedom ## Multiple R-squared: 0.7528, Adjusted R-squared: 0.7446 ## F-statistic: 91.38 on 1 and 30 DF, p-value: 1.294e-10
This slide displays the R code and the model summary (estimates, t-stats, R-squared).
# Fit multiple regression and create a prediction grid for a plane mod2 <- lm(mpg ~ wt + hp, data = mtcars) # grid for surface grid <- expand.grid( wt = seq(min(mtcars$wt), max(mtcars$wt), length.out = 25), hp = seq(min(mtcars$hp), max(mtcars$hp), length.out = 25) ) grid$mpg_pred <- predict(mod2, newdata = grid) # (The following creates a surface in plotly when viewed in the browser)
coef(model)).| Estimate | Std. Error | t value | Pr(>|t|) | |
|---|---|---|---|---|
| (Intercept) | 37.285126 | 1.877627 | 19.857575 | 0 |
| wt | -5.344472 | 0.559101 | -9.559044 | 0 |
lm documentation and ggplot2 / plotly help pages.*End of presentation