#load libraries
library(tidyverse)
library(broom)
#generate random data
data <- tibble(x = c(1.5, 2, 3.1, 3.9, 5),
y = c(3.7, 4.6, 5.5, 5.7, 7.2))
#view data
data
#genreate linear model
lm2_m1 <- lm(y ~ x , data = data)
#summarise linear model
lm2_m1s <- summary(lm2_m1)
#generate model diagnostics
lm2_m1d <- augment(lm2_m1, data=data)
#plot data and regression line
ggplot(lm2_m1d, aes(x = x, y = y))+
geom_point(size=4)+
geom_line(aes(x=x, y = .fitted), colour="blue", size=4)

#select only fitted and residual values
lm2_m1d %>%
select(.fitted, .resid)
## # A tibble: 5 x 2
## .fitted .resid
## <dbl> <dbl>
## 1 3.89 -0.192
## 2 4.34 0.256
## 3 5.34 0.160
## 4 6.06 -0.364
## 5 7.06 0.140
#exercise 2
inter <- 2.5
b1 <- 1.1
#generate new fitted values
data2 <- tibble(x = c(1.5, 2, 3.1, 3.9, 5),
y = inter+b1*(x))
#compare plot 1 to plot 2
plot_compare <- ggplot(data=data, aes(x = x, y = y))+
geom_point(size=4)+
geom_smooth(method="lm", se=FALSE, size=3)+
geom_line(data=data2, aes(x=x, y = y), size=3)
#add annotations
plot_compare +
geom_text(x = 2.0, y = 5.5, label = "Y = 2.50 + 1.10x", size=5)+
geom_text(x = 2.5, y = 4.0, label = "Y = 2.53 + 0.91x", size=5, colour="blue")
## `geom_smooth()` using formula 'y ~ x'
