demographics_model <- lm(fert_rate ~ life_exp, data = UN_data_ch5)with the moderndive package
one explanatory variable y ~ x
lm()coef()get_regression_points()geom_smooth()Fertility rate and life expectancy across countries
The model formula. Read the tilde as “is modeled by”. The response variable goes on the left, the explanatory variable on the right.
Response ~ Explanatory
Every modeling function in this chapter takes a formula and a data frame.
Fit a linear regression model: the single straight line that comes closest to every point in the cloud.
Fit a Linear Model
Example
the verb (function) the model formula response ~ explanatory the data frame
Pull the regression coefficients out of a fitted model: the intercept and the slope you interpret.
Read the Coefficients
Two numbers: the intercept, then the slope for the explanatory variable.
Example
the fitted model
the verb (function)
Return the fitted value and the residual for every observation, so you can see how far each point sits from the line.
Fitted Values & Residuals
residual = observed y minus fitted y-hat
Example
the fitted 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)
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)what kind of layer to add fit a straight line no confidence band
What the two regression coefficients actually mean.
Intercept & Slope