library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.1.1     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(ISLR)
data(Auto)
auto <- na.omit(Auto)
# Linear Regression
# 3.7 Conceptual Questions (2, 9, 10, 12)
# **2. Carefully explain the differences between the KNN classifier and KNN regression methods.**
# The differences between a KNN classifier and KNN regression method are that the KNN classifier uses data to classify new data points based on its distance to its neighbors, while the KNN regression creates a continuous outcome by averaging the observations in the same neighborhood.
# 9. This question involves the use of multiple linear regression on the
# Auto data set.
# (a) Produce a scatterplot matrix which includes all of the variables
# in the data set
plot(Auto)

# (b) Compute the matrix of correlations between the variables using
# the function cor(). You will need to exclude the name variable, cor() which is qualitative.
names(Auto)
## [1] "mpg"          "cylinders"    "displacement" "horsepower"   "weight"      
## [6] "acceleration" "year"         "origin"       "name"
cor(Auto[1:8])
##                     mpg  cylinders displacement horsepower     weight
## mpg           1.0000000 -0.7776175   -0.8051269 -0.7784268 -0.8322442
## cylinders    -0.7776175  1.0000000    0.9508233  0.8429834  0.8975273
## displacement -0.8051269  0.9508233    1.0000000  0.8972570  0.9329944
## horsepower   -0.7784268  0.8429834    0.8972570  1.0000000  0.8645377
## weight       -0.8322442  0.8975273    0.9329944  0.8645377  1.0000000
## acceleration  0.4233285 -0.5046834   -0.5438005 -0.6891955 -0.4168392
## year          0.5805410 -0.3456474   -0.3698552 -0.4163615 -0.3091199
## origin        0.5652088 -0.5689316   -0.6145351 -0.4551715 -0.5850054
##              acceleration       year     origin
## mpg             0.4233285  0.5805410  0.5652088
## cylinders      -0.5046834 -0.3456474 -0.5689316
## displacement   -0.5438005 -0.3698552 -0.6145351
## horsepower     -0.6891955 -0.4163615 -0.4551715
## weight         -0.4168392 -0.3091199 -0.5850054
## acceleration    1.0000000  0.2903161  0.2127458
## year            0.2903161  1.0000000  0.1815277
## origin          0.2127458  0.1815277  1.0000000
# (c) Use the lm() function to perform a multiple linear regression
# with mpg as the response and all other variables except name as
# the predictors. Use the summary() function to print the results.
# Comment on the output. For instance:
lm.fit2<-lm(mpg~. -name, data=Auto)
summary(lm.fit2)
## 
## Call:
## lm(formula = mpg ~ . - name, data = Auto)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -9.5903 -2.1565 -0.1169  1.8690 13.0604 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -17.218435   4.644294  -3.707  0.00024 ***
## cylinders     -0.493376   0.323282  -1.526  0.12780    
## displacement   0.019896   0.007515   2.647  0.00844 ** 
## horsepower    -0.016951   0.013787  -1.230  0.21963    
## weight        -0.006474   0.000652  -9.929  < 2e-16 ***
## acceleration   0.080576   0.098845   0.815  0.41548    
## year           0.750773   0.050973  14.729  < 2e-16 ***
## origin         1.426141   0.278136   5.127 4.67e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.328 on 384 degrees of freedom
## Multiple R-squared:  0.8215, Adjusted R-squared:  0.8182 
## F-statistic: 252.4 on 7 and 384 DF,  p-value: < 2.2e-16
#   i. Is there a relationship between the predictors and the response?
# we can see that based on the r^2 that mpg has a variance of .8215 related to its predictors.
#   ii. Which predictors appear to have a statistically significant relationship to the response?
#  displacement, weight, year, and origin all appear to have a significant relationship to the response.
#   iii. What does the coefficient for the year variable suggest?
# the coefficient for the year variable suggests that vehicles increase their mpg by .750773 for every year that passes. I guess they are becoming more efficient. 
# (d) Use the plot() function to produce diagnostic plots of the linear
# regression fit. Comment on any problems you see with the fit.
# Do the residual plots suggest any unusually large outliers? Does
# the leverage plot identify any observations with unusually high
# leverage?
par(mfrow=c(2,2))
plot(lm.fit2)

# The residual plots suggest(at least to me) shows some non-linearity but it seems to follow the trend of the red line. The leverage plot shows everything bunched together, with very few readings outside of -2, and 2.
# (e) Use the * and : symbols to fit linear regression models with
# interaction effects. Do any interactions appear to be statistically
# significant?
lm.fit3<-lm(mpg~weight*displacement, data=Auto[,1:8])
summary(lm.fit3)
## 
## Call:
## lm(formula = mpg ~ weight * displacement, data = Auto[, 1:8])
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -13.8664  -2.4801  -0.3355   1.8071  17.9429 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          5.372e+01  1.940e+00  27.697  < 2e-16 ***
## weight              -8.931e-03  8.474e-04 -10.539  < 2e-16 ***
## displacement        -7.831e-02  1.131e-02  -6.922 1.85e-11 ***
## weight:displacement  1.744e-05  2.789e-06   6.253 1.06e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.097 on 388 degrees of freedom
## Multiple R-squared:  0.7265, Adjusted R-squared:  0.7244 
## F-statistic: 343.6 on 3 and 388 DF,  p-value: < 2.2e-16
# in the weight * displacement interaction there is significance.
# Try a few different transformations of the variables, such as
# log(X), √
# X, X2. Comment on your findings.
plot(log(auto$weight), auto$mpg)

plot(sqrt(auto$weight), auto$mpg)

hist(log(auto$weight))

hist(sqrt(auto$weight))

hist(log(auto$mpg))

hist(sqrt(auto$mpg))

# Both the log and square root transformations seem to follow a linear trend. I ran a histogram with log to see if would be normal but it showed to be skewed and others seem to be fairly normal.
# 10. This question should be answered using the Carseats data set.
# (a) Fit a multiple regression model to predict Sales using Price,
# Urban, and US.
data(Carseats)
lm.fit4<-lm(Sales~Price+Urban+US, data=Carseats)
summary(lm.fit4)
## 
## Call:
## lm(formula = Sales ~ Price + Urban + US, data = Carseats)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -6.9206 -1.6220 -0.0564  1.5786  7.0581 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 13.043469   0.651012  20.036  < 2e-16 ***
## Price       -0.054459   0.005242 -10.389  < 2e-16 ***
## UrbanYes    -0.021916   0.271650  -0.081    0.936    
## USYes        1.200573   0.259042   4.635 4.86e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.472 on 396 degrees of freedom
## Multiple R-squared:  0.2393, Adjusted R-squared:  0.2335 
## F-statistic: 41.52 on 3 and 396 DF,  p-value: < 2.2e-16
# (b) Provide an interpretation of each coefficient in the model. Be
# careful—some of the variables in the model are qualitative!
# It seems US, and Urban are qualitative. They are categorical. But we can see in price that there is significance. We can see that with price   for every increase we see a return of -54.5. 
# (c) Write out the model in equation form, being careful to handle
# the qualitative variables properly.
# Sales = 13.043469 + (-0.054459)(Price) + (-0.021916)(Urban) + 1.200573(US) + ε
# Urban and US are both qualitative and a Yes response means the store is in an urban location, or in the US.
# (d) For which of the predictors can you reject the null hypothesis
# H0 : βj = 0?
# We can reject Price and US as they show significance. 
# (e) On the basis of your response to the previous question, fit a
# smaller model that only uses the predictors for which there is
# evidence of association with the outcome.
data(Carseats)
lm.fit5<-lm(Sales~Price+US, data=Carseats)
summary(lm.fit5)
## 
## Call:
## lm(formula = Sales ~ Price + US, data = Carseats)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -6.9269 -1.6286 -0.0574  1.5766  7.0515 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 13.03079    0.63098  20.652  < 2e-16 ***
## Price       -0.05448    0.00523 -10.416  < 2e-16 ***
## USYes        1.19964    0.25846   4.641 4.71e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.469 on 397 degrees of freedom
## Multiple R-squared:  0.2393, Adjusted R-squared:  0.2354 
## F-statistic: 62.43 on 2 and 397 DF,  p-value: < 2.2e-16
# (f) How well do the models in (a) and (e) fit the data?
# Both the models maintain the same R^2, where .2393 of the variance can be explained by the predictors. when removing the non-significant predictor the value didn't change by much.
# (g) Using the model from (e), obtain 95 % confidence intervals for
# the coefficient(s).
confint(lm.fit5)
##                   2.5 %      97.5 %
## (Intercept) 11.79032020 14.27126531
## Price       -0.06475984 -0.04419543
## USYes        0.69151957  1.70776632
# (h) Is there evidence of outliers or high leverage observations in the
# model from (e)?
par(mfrow = c(2, 2))
plot(lm.fit5)

# There is evidence of outliers as there are plots outside of -2 and 2 on the y axis and a few on the x axis. 
# 12. This problem involves simple linear regression without an intercept.
# (a) Recall that the coefficient estimate βˆ for the linear regression of
# Y onto X without an intercept is given by (3.38). Under what
# circumstance is the coefficient estimate for the regression of X
# onto Y the same as the coefficient estimate for the regression of
# Y onto X?
# The circumstance under which coefficient estimate for the regression of X onto Y is the same as Y onto X is if they are the same.Σx=Σy
#i dont know how to do all the subscript and superscript stuff to show the proper x to y regression coefficient.
# (b) Generate an example in R with n = 100 observations in which
# the coefficient estimate for the regression of X onto Y is different
# from the coefficient estimate for the regression of Y onto X.
set.seed(5)
x<-1:100
sum(x^2)
## [1] 338350
y <- 2 * x + rnorm(100, sd = 0.1)
sum(y^2)
## [1] 1353463
lm.fit.Y <- lm(y ~ x + 0)
lm.fit.X <- lm(x ~ y + 0)
summary(lm.fit.Y)
## 
## Call:
## lm(formula = y ~ x + 0)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.21922 -0.06060 -0.01270  0.07473  0.23474 
## 
## Coefficients:
##    Estimate Std. Error t value Pr(>|t|)    
## x 2.0000458  0.0001625   12305   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.09454 on 99 degrees of freedom
## Multiple R-squared:      1,  Adjusted R-squared:      1 
## F-statistic: 1.514e+08 on 1 and 99 DF,  p-value: < 2.2e-16
summary(lm.fit.X)
## 
## Call:
## lm(formula = x ~ y + 0)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.117308 -0.037331  0.006396  0.030315  0.109620 
## 
## Coefficients:
##    Estimate Std. Error t value Pr(>|t|)    
## y 5.000e-01  4.063e-05   12305   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.04727 on 99 degrees of freedom
## Multiple R-squared:      1,  Adjusted R-squared:      1 
## F-statistic: 1.514e+08 on 1 and 99 DF,  p-value: < 2.2e-16
# (c) Generate an example in R with n = 100 observations in which
# the coefficient estimate for the regression of X onto Y is the
# same as the coefficient estimate for the regression of Y onto X.
x <- 1:100
sum(x^2)
## [1] 338350
y <- 100:1
sum(y^2)
## [1] 338350
lm.fit.Y <- lm(y ~ x + 0)
lm.fit.X <- lm(x ~ y + 0)
summary(lm.fit.Y)
## 
## Call:
## lm(formula = y ~ x + 0)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -49.75 -12.44  24.87  62.18  99.49 
## 
## Coefficients:
##   Estimate Std. Error t value Pr(>|t|)    
## x   0.5075     0.0866    5.86 6.09e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 50.37 on 99 degrees of freedom
## Multiple R-squared:  0.2575, Adjusted R-squared:   0.25 
## F-statistic: 34.34 on 1 and 99 DF,  p-value: 6.094e-08
summary(lm.fit.X)
## 
## Call:
## lm(formula = x ~ y + 0)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -49.75 -12.44  24.87  62.18  99.49 
## 
## Coefficients:
##   Estimate Std. Error t value Pr(>|t|)    
## y   0.5075     0.0866    5.86 6.09e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 50.37 on 99 degrees of freedom
## Multiple R-squared:  0.2575, Adjusted R-squared:   0.25 
## F-statistic: 34.34 on 1 and 99 DF,  p-value: 6.094e-08