Introduction to Regression

Today

Today’s job: predict a county’s median household income. We’ll fit a line, read its slope in dollars, and check where it misses. You’ll use the same tools in Lab 7.

We’ll use lm() for the arithmetic. The harder part is saying what the answer means.

Start with a prediction

Pick a county. You know the share of adults who have a college degree. Can you make a decent guess about household income?

Make your guess before you scroll: Do counties with more college graduates tend to have higher incomes? How closely do you expect the dots to follow that pattern?

A scatterplot of college attainment and median household income for U.S. counties. The relationship is positive with substantial scatter. Michigan counties are orange, and Ingham and Ottawa are labeled.

Higher college shares generally go with higher incomes. Look at Ingham and Ottawa, though: similar college shares, very different incomes.

Ingham has the larger college share. Ottawa has the higher income. Education helps us predict income across counties, but it can’t settle every comparison. Let’s fit a line and see how much it helps.

The data and its units

We’ll use the U.S. Census Bureau’s 2020–2024 American Community Survey five-year estimates. The Census Bureau combines five years of survey responses to produce these estimates. All incomes use 2024 inflation-adjusted dollars.

Download the prepared file:

The file has 3,144 counties and county equivalents in the 50 states and D.C. One county has no usable income estimate. That leaves 3,143 counties for our examples. All three regressions use these same rows.

Variable Meaning Units
CollegePct Adults age 25+ with a bachelor’s degree or more Percent, from 0 to 100
IncomeK Median household income Thousands of 2024 dollars
PovertyPct Residents below the poverty threshold, among those for whom poverty status is determined Percent
MedianAge Median age of residents Years
Population Total population estimate People
CountyFIPS County identifier A five-character code, including leading zeros

Each dot represents a whole county. The median is the income of the middle household when we sort households from lowest to highest income. Households within that county can earn much more or much less.

We give each county the same weight in these regressions. A tiny county gets as much say in the fit as Wayne County.

Load it

library(tidyverse)
library(GGally)     # Scatterplot matrices

If you saved the CSV in your data folder, load it like this:

county_raw <- read_csv(
  "data/county_education_income_2024.csv",
  col_types = cols(
    CountyFIPS = col_character(),
    StateFIPS = col_character()
  )
)

You can also load the course copy directly:

county_raw <- read_csv(
  "https://ec242.netlify.app/data/county_education_income_2024.csv",
  col_types = cols(
    CountyFIPS = col_character(),
    StateFIPS = col_character()
  )
)

Keep FIPS codes as text. Otherwise, R can drop a leading 0 from a code. Next, remove rows that lack either variable in our first model:

counties <- county_raw %>%
  drop_na(CollegePct, IncomeK)

counties %>%
  select(County, State, CollegePct, IncomeK) %>%
  slice_head(n = 6)
# A tibble: 6 × 4
  County         State   CollegePct IncomeK
  <chr>          <chr>        <dbl>   <dbl>
1 Autauga County Alabama      29.1     72.5
2 Baldwin County Alabama      33.7     78.8
3 Barbour County Alabama      10.6     46.0
4 Bibb County    Alabama      11.7     52.5
5 Blount County  Alabama      15.8     64.2
6 Bullock County Alabama       8.12    31.3

Here’s the code for a simple version of that scatterplot:

ggplot(counties, aes(x = CollegePct, y = IncomeK)) +
  geom_point(alpha = 0.2) +
  labs(x = "College-educated adults (%)",
       y = "Median household income ($1,000s)") +
  theme_minimal()
NoteTRY IT: Check the Michigan numbers
  1. Filter the data to Michigan.
  2. Find Ingham and Ottawa. Compare their college shares and incomes.
  3. If income always rose with college share, which county would have the higher income? Does it?

Give the line a job

Start with the lowest-effort guess: give every county the same prediction. Use the average of the county median incomes, about $67,976. We’ll call this our baseline.

Careful with that number. We averaged county medians. We didn’t calculate the national median household income.

Now use CollegePct to let the prediction change from county to county. Does that beat our one-size-fits-all guess?

Two versions of the same county scatterplot. One has a horizontal line at the average county income; the other has an upward-sloping fitted regression line.

Left: one prediction for everyone. Right: the prediction changes with college share. The sloped line makes smaller total squared errors. We’ll calculate those errors below.

Here are the slope and intercept formulas from Tuesday:

\[ \widehat{\beta}_1 = r\frac{s_Y}{s_X}, \qquad \widehat{\beta}_0 = \bar{Y}-\widehat{\beta}_1\bar{X}. \]

The correlation tells us the direction and strength of the linear relationship. Multiplying by \(s_Y/s_X\) gives the slope its units: units of Y per unit of X.

Translate the formulas into R:

line_by_hand <- counties %>%
  summarize(
    mean_x = mean(CollegePct),
    mean_y = mean(IncomeK),
    sd_x = sd(CollegePct),
    sd_y = sd(IncomeK),
    r = cor(CollegePct, IncomeK)
  ) %>%
  mutate(
    slope = r * sd_y / sd_x,
    intercept = mean_y - slope * mean_x
  )

line_by_hand %>% select(r, intercept, slope)
# A tibble: 1 × 3
      r intercept slope
  <dbl>     <dbl> <dbl>
1 0.720      37.3  1.24

The line must pass through \((\bar{X}, \bar{Y})\), the point at the two sample means. Once we have the slope, the intercept formula puts the line through that point.

Fit the same line with lm()

That was the long route. For everyday use, let lm() fit the line:

education_model <- lm(IncomeK ~ CollegePct, data = counties)
coef(education_model)
(Intercept)  CollegePct 
      37.27        1.24 

Read the formula from left to right:

  • IncomeK is the response, or Y: the quantity we want to predict.
  • ~ means “modeled as a function of.”
  • CollegePct is the predictor, or X.
  • data = counties tells R where to find the columns.

We say that income is regressed on education. Keep the order straight. Predicting income from education asks a different question from predicting education from income. Swapping the variables changes the regression line, even though the correlation stays the same.

Save the model as education_model. Use coef() to pull out its coefficients: the intercept and slope.

b0 <- coef(education_model)[["(Intercept)"]]
b1 <- coef(education_model)[["CollegePct"]]

c(intercept = b0, slope = b1)
intercept     slope 
    37.27      1.24 

Same answers as before, with less typing. Our fitted equation is approximately

\[ \widehat{\text{IncomeK}} = 37.27 + 1.244\times\text{CollegePct}. \]

The hat means fitted or predicted. For a given college share, the line estimates the average county median income. Actual counties can sit above or below that estimate.

Interpret it in dollars

A one-unit increase in CollegePct means one percentage point: from 30% to 31%, for example. Keep “percentage point” in your explanation. It saves a lot of confusion.

Read the slope like this:

A one-percentage-point increase in a county’s college share corresponds to about $1,244 more in predicted median household income.

We’re comparing counties here. This slope can’t tell us how much one person’s income would change if they earned a degree.

Example 1: A ten-point difference

Going from 30% to 40% is a ten-percentage-point difference. Multiply the slope by ten:

10 * b1 * 1000
[1] 12436

A county scatterplot with a fitted line and an orange right-angle step between predicted incomes at college shares of 30 and 40 percent. The step labels the ten-point education change and its corresponding fitted income change.

Move ten percentage points right. Then move up to the line. That rise is ten times the slope. Both orange dots are predictions; neither represents an actual county.
NoteTRY IT: Fix this sentence

A classmate writes: “Getting a college degree raises household income by $1,244.”

Find two problems with that claim. Then rewrite it using what our county model can tell us.

Example 2: Make a prediction with predict()

What income does the line predict at CollegePct = 30? Plug in 30:

(b0 + b1 * 30) * 1000
[1] 74579

Use predict() to do several values at once. Put the values in a new table. Its predictor column must have the same name as the predictor in the model:

new_counties <- tibble(CollegePct = c(30, 40))

new_counties %>%
  mutate(predicted_income_dollars =
           1000 * predict(education_model, newdata = new_counties))
# A tibble: 2 × 2
  CollegePct predicted_income_dollars
       <dbl>                    <dbl>
1         30                   74579.
2         40                   87015.

We fit the model with IncomeK, so predict() returns thousands of dollars. Multiply by 1,000 to get dollars. R won’t do that conversion for you.

What about the intercept?

The intercept gives the prediction at CollegePct = 0: about $37,271. Before we build a story around it, check the data. The college shares range from about 0% to 80.5%.

Exactly one county has a zero in this file: Loving County, Texas. Its estimated population is 33. That’s a thin basis for a grand theory about places with no college graduates.

Here, the intercept mainly sets the line’s position. In other datasets, zero may fall outside the data entirely.

Example 3: Change the units, keep the relationship

Now fit the same model with income in dollars instead of thousands of dollars:

dollar_model <- lm(MedianIncome ~ CollegePct, data = counties)

coef(education_model)
(Intercept)  CollegePct 
      37.27        1.24 
coef(dollar_model)
(Intercept)  CollegePct 
      37271        1244 

The same fitted county relationship shown with income measured in thousands of dollars and in dollars. The lines have the same visual shape, while the reported slopes differ by a factor of one thousand.

Same dots, same line, different labels. Measuring income in dollars makes both coefficients 1,000 times larger. The correlation and R-squared stay the same.

A bigger coefficient doesn’t earn bragging rights. A slope of 1.244 and a slope of 1,243.6 describe the same relationship here. Report the units with the number.

Look at the mistakes

How far did the prediction miss? Subtract the fitted income from the observed income. For county \(i\), that difference is the residual:

\[ e_i = Y_i-\widehat{Y}_i. \]

  • A positive residual means observed income is above the line: we underpredicted.
  • A negative residual means observed income is below the line: we overpredicted.

Use fitted() for the predictions and resid() for the residuals:

county_results <- counties %>%
  mutate(
    fitted_income = fitted(education_model),
    residual = resid(education_model)
  )

county_results %>%
  filter(State == "Michigan",
         County %in% c("Ingham County", "Ottawa County", "Washtenaw County")) %>%
  select(County, IncomeK, fitted_income, residual)
# A tibble: 3 × 4
  County           IncomeK fitted_income residual
  <chr>              <dbl>         <dbl>    <dbl>
1 Ingham County       65.5          88.5   -23.0 
2 Ottawa County       90.5          85.7     4.84
3 Washtenaw County    89.2         110.    -21.1 

The education-income scatterplot with vertical orange segments between the fitted line and the observed values for Ingham, Ottawa, and Washtenaw counties. Labels show signed residuals.

Read each orange gap vertically: observed income minus fitted income. A gap tells us how far the model missed. It can’t tell us why.

The model guesses too high for Ingham and too low for Ottawa. What did it miss? Maybe household composition matters. Maybe industries, housing costs, or age matter.

Those are leads to investigate. We can’t pick the winning explanation from a residual alone.

NoteTRY IT: Find a county the line misses
  1. Use county_results to find the largest positive residual in Michigan.
  2. Find the most negative residual.
  3. For each, report the observed value, fitted value, and residual in dollars.
  4. Explain which county the model underpredicts and which it overpredicts.

Why this line? Squared errors

Add up the raw residuals and positive misses can cancel negative ones. Square them first. Now every nonzero miss adds to the total, and big misses count much more than small ones.

Ordinary least squares (OLS) chooses the intercept and slope with the smallest sum of squared errors, or SSE:

\[ \text{SSE}=\sum_{i=1}^{n}(Y_i-\widehat{Y}_i)^2. \]

Try three slopes. For each one, put the line through the two sample means. That gives each slope its best possible intercept.

Three county scatterplots with a line that is too flat, the OLS line, and a line that is too steep. Each panel reports its root mean squared error, with the smallest value for OLS.

OLS wins this comparison: it has the smallest squared-error total. The labels report RMSE, which puts the errors back in income units and ranks these lines in the same order.

Squared dollars are awkward to read. Root mean squared error (RMSE) puts the error measure back in the units of income. Average the squared residuals, then take the square root:

\[ \text{RMSE} =\sqrt{\frac{1}{n}\sum_{i=1}^{n}e_i^2}. \]

Our one-size-fits-all baseline has an RMSE of about $17,772. Adding education brings that down to about $12,338.

That’s an improvement on the data we used to fit the line. To check predictions for new counties, we’d need to test the model on data we held out.

Did we beat the baseline?

\(R^2\) reports the share of the baseline’s squared error that our line removes:

\[ R^2 =1-\frac{\sum_i(Y_i-\widehat{Y}_i)^2} {\sum_i(Y_i-\bar{Y})^2}. \]

sse_model <- sum(resid(education_model)^2)
sse_baseline <- sum((counties$IncomeK - mean(counties$IncomeK))^2)

1 - sse_model / sse_baseline
[1] 0.518
summary(education_model)$r.squared
[1] 0.518

Here, \(R^2\) is about 51.8%. Compared with our baseline, the line cuts total squared error by that share.

Don’t read that as “education causes 52% of income” or “we got 52% of counties exactly right.” \(R^2\) measures a reduction in squared error.

For a simple OLS regression with an intercept, \(R^2\) also equals the sample correlation squared. Conveniently, the name checks out.

Check where the line misses

A residual-versus-fitted scatterplot and a histogram of residuals for the county education model, both with zero reference lines.

Left: check how the residuals change as fitted income rises. Right: check the size and spread of the misses. Several counties earn much more than the line predicts.

Look at the long positive tail. Our model makes some very large underpredictions. A decent \(R^2\) leaves plenty of room for those.

Two more worked examples

Keep income as the response. Keep the same counties. Try a different predictor.

Example 4: A negative slope

What do you expect if we regress median household income on the poverty rate?

poverty_model <- lm(IncomeK ~ PovertyPct, data = counties)
coef(poverty_model)
(Intercept)  PovertyPct 
      98.80       -2.17 

A one-percentage-point higher poverty rate is associated with about $2,167 lower fitted median household income.

There’s a reason this relationship is strong: both variables describe the county’s incomes. The poverty rate already tells us something about who has low income. We’re describing the same period here, so don’t treat this as a forecast of future income.

Example 5: Age doesn’t get us very far

Could median age help? Older residents may earn more after years in the workforce. Retired households may earn less. The stories point in different directions. Let’s check the data:

age_model <- lm(IncomeK ~ MedianAge, data = counties)
coef(age_model)
(Intercept)   MedianAge 
     82.383      -0.344 
summary(age_model)$r.squared
[1] 0.011

Median age barely improves on the baseline. R still returns a slope, of course. Ask for a line and you’ll get a line. You have to decide whether it helps.

Three county scatterplots: income rises with college attainment, falls with poverty, and has a weak relationship with median age. Each panel gives its own slope and R-squared.

Education slopes up. Poverty slopes down. Both beat the age model by a lot. Each panel shows a separate regression with one predictor.

Check the far-right end of the poverty plot. The line predicts negative income. All the observed incomes are positive. Ope. The model misses that part of the pattern badly, despite its respectable \(R^2\).

NoteTRY IT: Compare the models
  1. Which model has the larger \(R^2\): education or poverty?
  2. Does a negative slope mean a model is bad?
  3. Would comparing the absolute slopes of the age and education models tell us which is more useful? Check their units before answering.

Explore several relationships

Four variables give us six pairs to inspect. A scatterplot matrix puts them in one figure:

county_numeric <- counties %>%
  select(CollegePct, IncomeK, PovertyPct, MedianAge)

ggpairs(
  county_numeric,
  columnLabels = c("College (%)", "Income ($1,000s)", "Poverty (%)", "Median age"),
  lower = list(continuous = wrap("points", alpha = 0.12, size = 0.4)),
  upper = list(continuous = wrap("cor", stars = FALSE, size = 4))
) +
  theme_minimal(base_size = 12)

A four-by-four scatterplot matrix for college attainment, income, poverty, and median age, with distributions on the diagonal and correlations in the upper triangle.

Scan one pair at a time. The diagonal shows distributions, the lower panels show scatterplots, and the upper panels report correlations. Open a full-size scatterplot when a pair catches your eye.

Don’t feed an ID code into cor() just because R stored it as a number. FIPS codes identify places. They are not measurements of how much “county” a place has.

A compact correlation picture

county_cor <- cor(county_numeric)
round(county_cor, 2)
           CollegePct IncomeK PovertyPct MedianAge
CollegePct       1.00    0.72      -0.46     -0.10
IncomeK          0.72    1.00      -0.73     -0.10
PovertyPct      -0.46   -0.73       1.00     -0.17
MedianAge       -0.10   -0.10      -0.17      1.00

Turn those numbers into a heatmap and you have a correlogram:

A triangular correlation heatmap for college attainment, income, poverty, and median age, with numeric correlations printed in each tile.

We only need one triangle: swapping X and Y gives the same correlation. The diagonal would be all ones. Income’s correlations with education and poverty are about equally strong, with opposite signs.
Show me how to build the heatmap with ggplot

First, turn the matrix into a long table with one row per pair. as.table() keeps the row and column labels. as.data.frame() puts them into columns.

cor_long <- as.data.frame(as.table(county_cor)) %>%
  rename(variable_x = Var1, variable_y = Var2, correlation = Freq) %>%
  filter(as.integer(variable_x) < as.integer(variable_y))

ggplot(cor_long, aes(variable_x, variable_y, fill = correlation)) +
  geom_tile(color = "white") +
  geom_text(aes(label = round(correlation, 2))) +
  scale_fill_gradient2(low = "#D9A27F", mid = "white", high = "#8DB4A3",
                       limits = c(-1, 1)) +
  coord_equal() +
  labs(x = NULL, y = NULL) +
  theme_minimal()

The filter() step keeps one triangle and drops the diagonal. Keep the numbers visible. Color helps us scan; the labels tell us what we’re looking at.

Four ways to fool yourself

Before you trust a line, check the scatterplot, unusual points, prediction range, and sample. Here’s how each can trip us up.

1. A curve can hide from correlation

Simulated positive, negative, and U-shaped relationships. Orange straight-line fits follow the first two patterns but miss the curve, whose correlation is near zero.

These dots are simulated. The U-shape is easy to see, but its correlation is near zero. One straight line can’t follow the drop and the rise.

Correlation measures a linear relationship. A small correlation can send you right past a strong curve. Plot the dots before you declare “nothing going on here.”

NoteTRY IT: Predict before calculating

Start at the left edge of the U. Move toward zero. What happens to Y? Now move from zero to the right edge. What changes? Explain why one slope can’t describe both parts well.

2. Some points pull the line harder

Two simulated datasets compare a high-residual point near the center of X with a high-residual point far outside the other X values. Original and refitted lines show a much larger slope change in the second case.

These examples are simulated. Left: a large residual near the mean of X barely changes the slope. Right: a point far out on X pulls the slope sharply. Check unusual points before deciding what to do with them.

A large residual means the line missed that observation by a lot. An influential point changes the fitted line by a lot when we include it. The pictures show why those can differ.

Inspect an unusual point. Check its units and source. Find out what it represents. “It ruined my beautiful regression” is not a data-cleaning rule.

3. R will predict past the data

The county scatterplot with its observed education range shaded, from zero to about eighty-one percent. The fitted line is solid green inside that range and dashed orange above it, up to one hundred percent.

Green: the range of college shares in our data. Dashed orange: the line extended beyond that range. R can calculate those extra predictions. We still need evidence that the pattern holds there.

Predicting beyond the observed X values is called extrapolation. Check the range before you report a prediction:

range(counties$CollegePct)
[1]  0.0 80.5

Check who the prediction is for, too. We fit this model to counties. Using it as a salary calculator for one graduate would change the question completely.

4. Change the sample, change the slope

Remember sampling variation from last week? It applies to slopes, too. Choose a different set of counties and you’ll usually get a different line.

Eight orange regression lines estimated from separate samples of fifty counties, overlaid on the county scatterplot. A thicker green line shows the fit using the full county file.

Each orange line uses a separate sample of 50 counties, drawn without replacement. Green uses the full file. This exercise shows what changes when we select different counties. The ACS survey margins of error are a separate source of uncertainty.

Try a sample of 50:

set.seed(15)

small_sample <- counties %>% slice_sample(n = 50)
small_model <- lm(IncomeK ~ CollegePct, data = small_sample)

coef(small_model)
(Intercept)  CollegePct 
      31.75        1.52 
coef(education_model)
(Intercept)  CollegePct 
      37.27        1.24 

Compare the two sets of coefficients. The small-sample slope won’t exactly match the full-file slope. We’ll put numbers on that uncertainty in a later lesson.

Your turn, then Lab 7

NoteTRY IT: Take the wheel

Use PovertyPct as the predictor and IncomeK as the response.

  1. Draw the scatterplot.
  2. Fit and save the model with lm().
  3. Extract the intercept and slope with coef().
  4. Explain the slope in one sentence. Include its units.
  5. Add the line with geom_abline(). Use the coefficients you extracted.
  6. Use predict() for poverty rates of 10% and 20%.
  7. Convert those predictions to dollars.
  8. Find the county with the largest positive residual.
  9. Explain what its positive residual means.

Here’s how to draw the line from a saved model. Adapt this code for your poverty model:

ggplot(counties, aes(CollegePct, IncomeK)) +
  geom_point(alpha = 0.2) +
  geom_abline(
    intercept = coef(education_model)[["(Intercept)"]],
    slope = coef(education_model)[["CollegePct"]],
    color = "#18453B"
  ) +
  theme_minimal()

geom_smooth(method = "lm", se = FALSE) draws the same line. Saving the model also lets you pull out coefficients, predictions, and residuals.

In Lab 7, you’ll switch to Ames home sales. Same moves: plot, fit, read the coefficients, check the residuals. Watch the order of the variables around ~. Keep the response units handy.

Before you pack up: What would you tell someone who used our county slope to predict the raise they’d get from a college degree?