libraries

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ purrr   0.3.4 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ stringr 1.4.1 
## ✔ readr   2.1.2      ✔ forcats 0.5.2 
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(moderndive)

import data

df <- tribble(
  ~x, ~y,
  -3, 5,
   4, 1,
   8, 7,
  -6, -9
)

1. find linear regression line

get_regression_table(lm(y ~ x, data=df))

y = 0.782x + 0.413

2. Table of residuals

get_regression_points(lm(y ~ x, data=df))

graph showing points and line

ggplot(df, aes(x,y)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)
## `geom_smooth()` using formula 'y ~ x'

4. add red error lines

df <- get_regression_points(lm(y ~ x, data=df)) %>% left_join(df)
## Joining, by = c("y", "x")
df
ggplot(df, aes(x,y)) +
  geom_segment(aes(xend = x, yend = y_hat), color='red', size=1.5) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)
## `geom_smooth()` using formula 'y ~ x'