02/01/2024

Introduction

Simple linear regression is a commonly used type of predictive analysis. The idea is to examine (1) does a set of predictor variables do a good job in predicting an outcome? (2) Which variables in particular are significant predictors of the outcome variable, and how do they impact the outcome?

library(ggplot2)
library(plotly)

Simple Linear Regression Equation

\[ y = \beta_0 + \beta_1x + \epsilon \]

  • \(y\) is the dependent variable.
  • \(x\) is the independent variable.
  • \(\beta_0\) is the y-intercept.
  • \(\beta_1\) is the slope.
  • \(\epsilon\) is the error term.

Understanding the Coefficients

The coefficients in a simple linear regression model, \(\beta_0\) and \(\beta_1\), are important for understanding the relationship between the independent and dependent variables.

  • Intercept (\(\beta_0\)): Represents the expected value of \(y\) when \(x\) is 0.

  • Slope (\(\beta_1\)): Indicates the expected change in \(y\) for a one-unit change in \(x\).

The equation \(y = \beta_0 + \beta_1x + \epsilon\) can be interpreted as:

  • For every one-unit increase in \(x\), \(y\) is expected to increase by \(\beta_1\) units, holding all other factors constant.

Example Dataset

We will use the mtcars dataset for the regression analysis, predicting mpg (miles per gallon) based on the wt (weight of the car).

summary(mtcars$mpg)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   10.40   15.43   19.20   20.09   22.80   33.90
summary(mtcars$wt)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   1.513   2.581   3.325   3.217   3.610   5.424

Scatter Plot with ggplot2

ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  geom_smooth(method="lm", col="blue") + theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

Fitting a Simple Linear Regression Model

fit <- lm(mpg ~ wt, data=mtcars)
fit_summary <- capture.output(summary(fit))

Call: lm(formula = mpg ~ wt, data = mtcars)

Residuals: Min 1Q Median 3Q Max -4.5432 -2.3647 -0.1252 1.4096 6.8727

Coefficients: Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.2851 1.8776 19.858 < 2e-16 wt -5.3445 0.5591 -9.559 1.29e-10 — Signif. codes: 0 ‘’ 0.001 ’’ 0.01 ’’ 0.05 ‘.’ 0.1 ’ ’ 1

Residual standard error: 3.046 on 30 degrees of freedom Multiple R-squared: 0.7528, Adjusted R-squared: 0.7446 F-statistic: 91.38 on 1 and 30 DF, p-value: 1.294e-10

Coefficients Plot

coefficients <- data.frame(term=names(coef(fit)), estimate=coef(fit))
ggplot(coefficients, aes(x=term, y=estimate, fill=term)) +
  geom_bar(stat="identity") + theme_minimal()

3D Plot with plotly

p <- plot_ly(data = mtcars, x = ~wt, y = ~mpg, z = ~disp,
             type = 'scatter3d', mode = 'markers')
p