Using the “cars” dataset in R, build a linear model for stopping distance as a function of speed and replicate the analysis of your textbook chapter 3 (visualization, quality evaluation of the model, and residual analysis.)

Dataset

dim(cars)
## [1] 50  2

The cars dataset has 50 observations and 2 variables.

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Visualization

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.0.5
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.0.5
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
cars_speed_df = arrange(cars, speed)

ggplot(data=cars_speed_df, aes(cars_speed_df$speed)) + 
  geom_histogram(aes(fill = ..count..)) +
  scale_fill_gradient("Count", low = "lightblue", high = "darkblue") +
  labs(title = "Historgram - Speed") +
  labs(x = "speed") +
  labs(y = "Count")
## Warning: Use of `cars_speed_df$speed` is discouraged. Use `speed` instead.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

cars_dist_df = arrange(cars, dist)

ggplot(data=cars_dist_df, aes(dist)) + 
  geom_histogram(aes(fill = ..count..), bins = 30) +
  scale_fill_gradient("Count", low = "indianred1", high = "red3") +
  labs(title = "Historgram - Distance") +
  labs(x = "dist") +
  labs(y = "Count")

Model evaluation

This linear model is based on a single factor regression. speed is the independent variable (input) and stopping distance is the dependent variable (output).

cars.lm <- lm(dist ~ speed, data = cars)
summary(cars.lm)
## 
## Call:
## lm(formula = dist ~ speed, data = cars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -29.069  -9.525  -2.272   9.215  43.201 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -17.5791     6.7584  -2.601   0.0123 *  
## speed         3.9324     0.4155   9.464 1.49e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.38 on 48 degrees of freedom
## Multiple R-squared:  0.6511, Adjusted R-squared:  0.6438 
## F-statistic: 89.57 on 1 and 48 DF,  p-value: 1.49e-12

From above we see, intercept = -17.5791, slope = 3.9324.

\(dist= −17.5791 + 3.9324∗speed\)

plot(cars, xlab = "Speed", ylab = "Stopping distance")
abline(cars.lm)

Residual Analysis

plot(fitted(cars.lm), resid(cars.lm))

QQ Plots

The QQ plots shows skew at right, if the QQ plot follow a straight line then we can say residuals are normally distributed. Since QQ plot here is skewed residuals are not normally distributed.

qqnorm(resid(cars.lm))
qqline(resid(cars.lm))