Introduction

Simple linear regression aims to find a linear relationship to describe the correlation between an independent and possibly dependent variable.

\[y = \beta_0 + \beta_1 x +\varepsilon \]

where \(\beta_0\) is the intercept, \(\beta_1\) is the slope, and \(\varepsilon\) is the error term.

Dataset: ‘mtcars’

Using the built-in data set of ‘mtcars’ to model the miles per gallon based on the horsepower.

##                               model  mpg  hp    wt
## Mazda RX4                 Mazda RX4 21.0 110 2.620
## Mazda RX4 Wag         Mazda RX4 Wag 21.0 110 2.875
## Datsun 710               Datsun 710 22.8  93 2.320
## Hornet 4 Drive       Hornet 4 Drive 21.4 110 3.215
## Hornet Sportabout Hornet Sportabout 18.7 175 3.440
## Valiant                     Valiant 18.1 105 3.460

Linear Fit

## 
## Call:
## lm(formula = mpg ~ hp, data = mtcars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -5.7121 -2.1122 -0.8854  1.5819  8.2360 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 30.09886    1.63392  18.421  < 2e-16 ***
## hp          -0.06823    0.01012  -6.742 1.79e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.863 on 30 degrees of freedom
## Multiple R-squared:  0.6024, Adjusted R-squared:  0.5892 
## F-statistic: 45.46 on 1 and 30 DF,  p-value: 1.788e-07

Plot of mtcars mpg vs. hp

R code explaining Plot of mtcars

The data set used is mtcars.

x = horsepower

y = miles per gallon

the use of geom_point(color = ‘blue’), shows a scatter plot with blue dots.

the labs() is for the labels of the title, x-axis, and y-axis.

using theme_minimal() removes grid-lines and removes the border.

ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point(color = 'blue') +
  labs(title = 'Mpg vs Horsepower', x = 'Horsepower', y = 'Mpg') +
  theme_minimal()

Coefficients for fitted

From the model:

\[ \hat{y} = \hat{\beta}_0 + \hat{\beta}_1 x \]

The estimated coefficients are:

  • \(\hat{\beta}_0 =\) 30.1
  • \(\hat{\beta}_1 =\) -0.07

Fitted line Plot

## `geom_smooth()` using formula = 'y ~ x'

##3D render