########## 2.1 ##########
gpa <- c(2.8,3.4,3.0,3.5,3.6,3.0,2.7,3.7); #y
act <- c(21,24,26,27,29,25,25,30); #x

#a)
n = length(gpa)

x_line = sum(act)/n
y_line = sum(gpa)/n

Sxx = sum(sapply(act, function(x) {(x - x_line)^2})) /n
Sxy = sum(mapply(function(x, y) {(x - x_line)*(y - y_line)}, act, gpa)) /n

b2 = Sxy/Sxx
b1 = y_line - b2*x_line


#b)
y_hat = b1+b2*act

lm<-lm(gpa~act);
#summary(lm);

plot(gpa~act);
abline(lm);
points(act, y_hat, pch=2)

########## 2.2 ##########
#b)
#u_hat = gpa - y_hat
#sum(u_hat)

sum(lm$residuals)


#c)
b1+b2*20

########## 2.3 ##########
wagedata = read.table("wagedata.csv")
fnk = lm(wage ~ educ, data = wagedata)

#a)
fnk


#b)
b1 = fnk[["coefficients"]][["(Intercept)"]]
b2 = fnk[["coefficients"]][["educ"]]

yi = wagedata$wage
xi = wagedata$educ

y_hat = b1+b2* xi
u_hat = yi-y_hat

plot(xi, u_hat)

#or
plot(wagedata$educ, fnk$residuals)
