Simple linear regression

with the moderndive package

one explanatory variable y ~ x

  • lm()
  • coef()
  • get_regression_points()
  • geom_smooth()

Fertility rate and life expectancy across countries

y ~ x

The model formula. Read the tilde as “is modeled by”. The response variable goes on the left, the explanatory variable on the right.

Every modeling function in this chapter takes a formula and a data frame.

lm()

Fit a linear regression model: the single straight line that comes closest to every point in the cloud.

lm()

Example

demographics_model <- lm(fert_rate ~ life_exp, data = UN_data_ch5)

the verb (function) the model formula response ~ explanatory the data frame

coef()

Pull the regression coefficients out of a fitted model: the intercept and the slope you interpret.

Two numbers: the intercept, then the slope for the explanatory variable.

coef()

Example

the fitted model

coef(demographics_model)
(Intercept)    life_exp 
 12.5992926  -0.1372879 

the verb (function)

get_regression_points()

Return the fitted value and the residual for every observation, so you can see how far each point sits from the line.

residual = observed y minus fitted y-hat

get_regression_points()

Example

the fitted model

get_regression_points(demographics_model)
# A tibble: 181 × 5
     ID fert_rate life_exp fert_rate_hat residual
  <int>     <dbl>    <dbl>         <dbl>    <dbl>
1     1       4.3     53.6          5.23   -0.934
2     2       1.4     79.5          1.69   -0.289
3     3       2.7     78.0          1.89    0.813
4     4       5       62.1          4.07    0.928
# ℹ 177 more rows

the verb (function)

geom_smooth()

Draw the regression line on top of a scatterplot.

Example

ggplot(UN_data_ch5, aes(x = life_exp, y = fert_rate)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

Scatterplot of fertility rate against life expectancy for 181 UN member states: fertility runs from about 1 to 6.6 births per woman and falls as life expectancy rises from about 54 to 86 years, with a straight regression line sloping down through the cloud

what kind of layer to add fit a straight line no confidence band

Interpreting

What the two regression coefficients actually mean.

  • The intercept is the fitted value when x is zero.
  • The slope is the change in y for a one-unit increase in x.
  • A residual is what the model missed for one observation.
  • Correlation measures strength; the slope carries the units.