########## 4.6 ##########
wagedata = read.table("wagedata.csv")

log_edu = lm(log(wage) ~ educ + exper, data = wagedata)
sq_log_edu = lm(log(wage) ~ educ + exper + I(exper*exper), data = wagedata)

#a)
summary(log_edu) #R-squared:  0.2493, Adjusted R-squared:  0.2465
summary(sq_log_edu) #R-squared:  0.3003, Adjusted R-squared:  0.2963

#The squared regression has a better fit since it can use one explanatory variable more
#The value we should look at is the adjusted Rē since it takes the number of variables into account


#b)
b_exp = sq_log_edu$coefficients["exper"]
b_exp2 = sq_log_edu$coefficients["I(exper * exper)"]
exper = wagedata$exper

plot(exper, b_exp*exper+b_exp2*exper*exper)
#This shows the influence of the squared eperience. After 30 jears the influence of experience goes down again but it always is > 0


#c)
#Yes in the first regression, no in the second expression because it has both exper and exper^2 and you can't keep both fixed when changing exper, instead you would have to look at the graph from b)

########## 4.7 ##########
bwght = read.table("bwght.csv", header=TRUE, sep = ",")


#a)
weight = lm(bwght ~ cigs + faminc, data = bwght)
summary(weight)
#cigs is negative (more -> smaller) and faminc is positive (more -> bigger), both were expected
#The intercept is also very high, meaning the overall impact of both is highly dependent on their amount
#Rē is relatively low at 0.0298


#b)
ounce_to_gramm = 28.3495
bwght2 = bwght
bwght2$bwght = bwght$bwght * ounce_to_gramm

weight2 = lm(bwght ~ cigs + faminc, data = bwght2)
summary(weight2)

#Rē still is 0.0298, all other betas are also (nearly) equal after conversion
116.97413 * ounce_to_gramm #Intercept: 3316.158 converted, now 3316.1581
-0.46341 * ounce_to_gramm #cigs: -13.13744 converted, now -13.1374
0.09276 * ounce_to_gramm #faminc: 2.6297 converted, now 2.6298


#c)
weight_nI = lm(bwght ~ cigs + faminc + 0, data = bwght)

summary(weight_nI) #0.7237
1 - sum(weight_nI$residuals^2) / sum(bwght$bwght^2) #0.7236727
sum(weight_nI$fitted.values^2) / sum(bwght$bwght^2) #0.7236727
