Q1)

Q2)

Q3)

Q4)

(a)

y <- c(13, 19, 15, 9, 22)
x <- c(3, 5, 4, 2, 6)

df <- data.frame(wk = 1:5, x = x, y = y); df
##   wk x  y
## 1  1 3 13
## 2  2 5 19
## 3  3 4 15
## 4  4 2  9
## 5  5 6 22
# Part a : 
plot(x=df$x, y=df$y)

# R's calc
mdl <- lm(y ~ x,data=df); mdl$coefficients
## (Intercept)           x 
##         2.8         3.2
X_mat <- matrix(c(rep(1,5), df$x), ncol =2)

XTX_mat <- t(X_mat)%*%X_mat

beta_hat <- solve(XTX_mat)%*%t(X_mat)%*% as.matrix(df$y); beta_hat # Same as mdl so its right
##      [,1]
## [1,]  2.8
## [2,]  3.2

(b)

(c)

# Part c : 
plot(df$x, df$y, cex=.4,pch = 19, col = "blue",
     main = "OLS Fit",
     xlab = "x", ylab = "y")

abline(mdl, col = "green", lwd = 2)

y_hat <- fitted(mdl)          
residuals <- resid(mdl)       

segments(x0 = df$x, y0 = df$y, 
         x1 = df$x, y1 = y_hat, 
         col = "red", lwd = 1.5)

# verify e :
df$y - fitted(mdl)
##    1    2    3    4    5 
##  0.6  0.2 -0.6 -0.2  0.0
mdl$coefficients
## (Intercept)           x 
##         2.8         3.2

(d)

(e)

Q5)

Q6)