2024-02-05

What is simple linear regression?

Simple linear regression is a statistical method to model the relationship between a single independent variable and a dependent variable.

Mathematical Formula

The simple linear regression model can be represented as:

\[ Y = \beta_0 + \beta_1 \cdot X + \epsilon \] Where: \(Y\) is the dependent variable \(X\) is the independent variable \(\beta_0\) is the intercept \(\beta_1\) is the slope \(\epsilon\) is the error term

Example Dataset mtcars

## # A tibble: 6 × 11
##   manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class 
##   <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr> 
## 1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compa…
## 2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compa…
## 3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compa…
## 4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compa…
## 5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compa…
## 6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compa…

Understanding Residuals

In the context of linear regression, residuals are the differences between the observed values (\(Y\)) and the predicted values (\(\hat{Y}\)) from the regression model.

\[e_i = Y_i - \hat{Y}_i\]

{\(Y_i\):} Observed value of the dependent variable.
{\(\hat{Y}_i\):} Predicted value of the dependent variable based on the regression model.

Key Points
-Residuals quantify the degree to which the model’s predictions differ from the actual data.
-Positive residuals indicate overestimation, while negative residuals indicate underestimation.
-Residuals help assess the model’s goodness of fit and identify potential issues, such as outliers or patterns.

Scatterplot mpg; City MPG vs. Highway MPG

Residuals scatterplot for mpg

Plotlyfication of previous two plots

R Code to create residuals scatterplot

# Fit simple linear regression
lm_model <- lm(cty ~ hwy, data = data)

# Calculate residuals
residuals <- resid(lm_model)

# Create ggplot graph for residuals
residuals_plot <- ggplot(data, aes(x = hwy, y = residuals, 
                                   color = manufacturer)) +
  geom_point() + geom_hline(yintercept = 0, linetype = "dashed",
                            color = "red") +
  labs(title = "Residuals Plot",
       x = "Highway MPG",
       y = "Residuals") +
  theme_minimal()

# Display graph for residuals
residuals_plot