--- title: "Graphing Residuals" date: 'Last compiled: `r format(Sys.time(), "%A, %B %d, %Y - %X.")`' author: 'Alan T. Arnholt' output: bookdown::html_document2 --- ```{r label = "setup", include = FALSE, message = FALSE} library(ggplot2) knitr::opts_chunk$set(echo = TRUE, comment = NA, fig.align = "center", warning = FALSE, message = FALSE) ``` # (APPENDIX) Appendix A {-} ## Residuals The $i^{th}$ residual is defined as $\hat{\epsilon}_i = y_i - \hat{y}_i$. ```{r} library(dplyr) library(PASWR2) head(HSWRESTLER) null <- lm(hwfat ~ 1, data = HSWRESTLER) summary(null) HSWRESTLER %>% summarize(Intercept = mean(hwfat)) slr <- lm(hwfat ~ abs, data = HSWRESTLER) summary(slr) ``` * Use the function `augment` from the `broom` package ```{r} library(broom) slr %>% augment() %>% head() %>% round(3) NDF <- slr %>% augment() ``` ## Graphing ```{r} ggplot(data = NDF, aes(x = abs, y = hwfat)) + geom_point(color = "purple") + theme_bw() + geom_smooth(method = "lm", se = FALSE, color = "gray") + geom_segment(aes(x = abs, xend = abs, y = hwfat, yend = .fitted), size = 0.25) ``` ```{r} ggplot(data = NDF, aes(x = abs, y = hwfat)) + geom_point(color = "purple") + theme_bw() + geom_line(aes(x = abs, y = .fitted), color = "gray") + geom_segment(aes(x = abs, xend = abs, y = hwfat, yend = .fitted), size = 0.25) ``` ```{r} ndf1 <- augment(slr) ndf2 <- augment(null) ndf2$abs <- HSWRESTLER$abs ndf <- bind_rows(ndf1, ndf2) %>% mutate(model = rep(c("slr", "null"), each = 78)) DT::datatable(ndf) ``` ```{r, fig.width = 8} ggplot(data = ndf, aes(x = abs, y = hwfat)) + facet_grid(.~ model) + geom_line(aes(x = abs, y = .fitted), color = "gray") + theme_bw() + geom_segment(aes(x = abs, xend = abs, y = hwfat, yend = .fitted), size = 0.25, linetype = "dotted") + geom_point(color = "lightblue") ``` ### Something Else