library(ISLR2)
library(readr)
Auto <- read_csv("Auto.csv")
## Rows: 397 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): horsepower, name
## dbl (7): mpg, cylinders, displacement, weight, acceleration, year, origin
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(Auto)
## # A tibble: 6 × 9
##     mpg cylinders displacement horsepower weight acceleration  year origin name 
##   <dbl>     <dbl>        <dbl> <chr>       <dbl>        <dbl> <dbl>  <dbl> <chr>
## 1    18         8          307 130          3504         12      70      1 chev…
## 2    15         8          350 165          3693         11.5    70      1 buic…
## 3    18         8          318 150          3436         11      70      1 plym…
## 4    16         8          304 150          3433         12      70      1 amc …
## 5    17         8          302 140          3449         10.5    70      1 ford…
## 6    15         8          429 198          4341         10      70      1 ford…
data(Auto)
lm_fit=lm(mpg~horsepower,Auto)
summary(lm_fit)
## 
## Call:
## lm(formula = mpg ~ horsepower, data = Auto)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -13.5710  -3.2592  -0.3435   2.7630  16.9240 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 39.935861   0.717499   55.66   <2e-16 ***
## horsepower  -0.157845   0.006446  -24.49   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.906 on 390 degrees of freedom
## Multiple R-squared:  0.6059, Adjusted R-squared:  0.6049 
## F-statistic: 599.7 on 1 and 390 DF,  p-value: < 2.2e-16
#i.Yes, there is a relationship between horsepower and mpg as deterined by testing the null hypothesis of all regression coefficients equal to zero. Since the F-statistic is far larger than 1 and the p-value of the F-statistic is close to zero we can reject the null hypothesis and state there is a statistically significant relationship between horsepower and mpg.
#ii.The relationship between horsepower and mpg is moderately strong, with an R-squared value of 60.59%, meaning horsepower explains about 60.59% of the variation in mpg. The negative coefficient indicates that as horsepower increases, mpg decreases, showing an inverse relationship.
#iii.MPG has a negative linear relationship with horsepower. For every unit increase in horsepower, the mpg falls by -0.158mpg.
#iv.
predict(lm_fit, data.frame(horsepower=c(98)), interval='prediction')
##        fit     lwr      upr
## 1 24.46708 14.8094 34.12476
predict(lm_fit, data.frame(horsepower=c(98)), interval='confidence')
##        fit      lwr      upr
## 1 24.46708 23.97308 24.96108
#b
attach(Auto)
plot(horsepower, mpg)
abline(lm_fit)

#c
par(mfrow=c(2,2))
plot(lm_fit)