2024-06-04

Dataset cars

data(cars)
head(cars)
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10

This data set explores the stopping distance of cars in correlation with their speed before stopping. I will be modeling this data with simple linear regression.

Dataset cars; Speed v.s. Stopping Distance Graph Setup

mod = lm(dist ~ speed, data=cars)
x = cars$speed; y = cars$dist
x_axis <- list(
  title = "Speed (mph)",
  titlefont = list(family="Modern Computer Roman")
)
y_axis <- list(
  title = "Stopping Distance (ft)",
  titlefont = list(family="Modern Computer Roman"),
  range = c(0,100)
)
fig <- plot_ly(x=x, y=y, type="scatter", mode="markers", name="data",
               width=800, height=430) %>%
        add_lines(x=x, y=fitted(mod), name="fitted") %>%
        layout(xaxis = x_axis, yaxis = y_axis) %>%
        layout(margin=list(
          l=150,
          r=50,
          b=20,
          t=40
          )
        )
config(fig, displaylogo=FALSE)

Dataset cars; Speed v.s. Stopping Distance Graph in Plotly

Dataset cars; Speed v.s. Stopping Distance Model Equation

While the correlation is not strong, it is clear that there is a positive correlation between the speed. The general equation for simple linear regression is shown below.

model: \(\text{Speed} = \beta_0 + \beta_1 \cdot \text{Stopping Distance} + \varepsilon; \hspace{1cm} \varepsilon \sim \mathcal{N}(0; \sigma^2)\)

This equation displays a linear relationship between the speed of the car and its stopping distance at that speed by calculating a deterministic linear term and adding some amount of error.

Dataset cars; Speed v.s. Stopping Distance Fitted Line Equation

It can be useful to see an equation that estimates the output value of data in many cases.

fitted: \(\text{Speed} = \hat{\beta}_0 + \hat{\beta}_1 \cdot \text{Stopping Distance}\)
\(\hat{\beta}_0 = b_0 - \text{estimate of }\beta_0\)
\(\hat{\beta}_1 = b_1 - \text{estimate of }\beta_1\)

The fitted line attempts to show what the expected y value is for a given x.

Dataset cars; Speed v.s. Stopping Distance Scatterplot in ggplot2

Dataset cars; Speed v.s. Stopping Distance Fitted Line in ggplot2

I will modify the scatterplot shown in the previous slide to add a line of best fit for the data.