STAT 1080 - Fall 2026
  • Course Info
    • Overview
    • Syllabus
    • Support
    • Schedule
    • Useful links
  • Weekly Materials
    • W1. Introduction
    • W2. RStudio
    • W3. Correlation
    • W4. Programming
    • W5. Tidyverse
    • W6. Dates/Times and Distributions
    • W7. Data Visualization
    • W8. Statistics & Probability
    • W9. Data & Probability
    • W10. Random Variables
    • W11. Parameters & Estimates
    • W12. Statistical Inference
    • W13. Regression
    • W14. Regression
    • W15. Project Meetings

On this page

  • Case study: is height hereditary?
  • The correlation coefficient
    • Sample correlation is a random variable
  • The regression line
    • Linear regression improves precision
    • Bivariate normal distribution justification
  • Report an issue

Tidyverse Code for Linear Regression

Case study: is height hereditary?

library(dslabs)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(tidyr)
library(ggplot2)
library(HistData)
data("GaltonFamilies")
set.seed(1983)
galton <- as.data.frame(GaltonFamilies)

galton_sample <- GaltonFamilies |>
  filter(gender == "male") |>
  group_by(family) |>
  # Get a single, randomly selected male child
  slice_sample(n = 1) |> 
  ungroup() |>
  select(
    father,
    # rename to son
    son = childHeight 
  )

We can compute summary stats for this dataset:

galton_sample |>
  summarise(
    mean_father = mean(father),
    sd_father   = sd(father),
    mean_son    = mean(son),
    sd_son      = sd(son)
  )
# A tibble: 1 × 4
  mean_father sd_father mean_son sd_son
        <dbl>     <dbl>    <dbl>  <dbl>
1        69.1      2.55     69.2   2.71

(I’m going to be more picky about this and force the x and y axis coordinates to be the same)

galton_sample |> ggplot(aes(father, son)) + 
  geom_point(alpha = 0.5) + 
  coord_cartesian(xlim = c(60, 80), ylim = c(60, 80), ratio = 1) + 
  theme_bw()

The correlation coefficient

with(galton_sample, cor(father, son))
[1] 0.4334102

Sample correlation is a random variable

r <- galton_sample |>
  slice_sample(n = 25, replace = TRUE) |>
  summarise(r = cor(father, son)) |>
  pull(r)

r
[1] 0.4630811
library(infer)
r <- galton_sample |>
  rep_slice_sample(reps = 1000, n = 25, replace = TRUE) |>
  summarise(r = cor(father, son))
ggplot(r, aes(x = r)) + geom_histogram(color = "black", fill = "grey") + theme_bw()
`stat_bin()` using `bins = 30`. Pick better value `binwidth`.

mean(r$r)
[1] 0.4291816
sd(r$r)
[1] 0.1663783
library(qqplotr) # Makes nicer qq plots (imo)

Attaching package: 'qqplotr'
The following objects are masked from 'package:ggplot2':

    stat_qq_line, StatQqLine
ggplot(data = r, aes(sample = r)) + 
  stat_qq_point() + 
  stat_qq_line() + 
  coord_fixed() +
  theme_bw() + ylab("Sample Quantile") + xlab("Theoretical Quantile")

ggplot(data = r, aes(sample = r)) + 
  stat_qq_band() + 
  stat_qq_line() +
  stat_qq_point(bandtype = "ts", conf = .95) + 
  theme_bw() + ylab("Sample Quantile") + xlab("Theoretical Quantile")
Warning in stat_qq_point(bandtype = "ts", conf = 0.95): Ignoring unknown
parameters: `bandtype` and `conf`

r40 <- galton_sample |>
  rep_slice_sample(reps = 1000, n = 40, replace = TRUE) |>
  summarise(r = cor(father, son))

ggplot(data = r40, aes(sample = r)) + 
  stat_qq_band() + 
  stat_qq_line() +
  stat_qq_point() + 
  theme_bw() + ylab("Sample Quantile") + xlab("Theoretical Quantile")

r50 <- galton_sample |>
  rep_slice_sample(reps = 1000, n = 50, replace = TRUE) |>
  summarise(r = cor(father, son))

ggplot(data = r50, aes(sample = r)) + 
  stat_qq_band() + 
  stat_qq_line() +
  stat_qq_point() + 
  theme_bw() + ylab("Sample Quantile") + xlab("Theoretical Quantile")

The regression line

fit <- lm(son ~ father, data = galton_sample)
summary(fit)

Call:
lm(formula = son ~ father, data = galton_sample)

Residuals:
    Min      1Q  Median      3Q     Max 
-9.3543 -1.5657 -0.0078  1.7263  9.4150 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 37.28761    4.98618   7.478 3.37e-12 ***
father       0.46139    0.07211   6.398 1.36e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.45 on 177 degrees of freedom
Multiple R-squared:  0.1878,    Adjusted R-squared:  0.1833 
F-statistic: 40.94 on 1 and 177 DF,  p-value: 1.36e-09
print(coef(fit))
(Intercept)      father 
  37.287605    0.461392 
params <- coef(fit) # get slope and intercept from lm directly
ggplot(galton_sample, aes(x = father, y = son)) +
  geom_point(alpha = 0.5) +
  # blue line
  geom_smooth(method = "lm", se = FALSE) +
  # black line
  geom_abline(slope = params[2], intercept =  params[1]) +
  labs(title = "Regression Line") + 
  coord_cartesian(xlim = c(60, 80), ylim = c(60, 80), ratio = 1) + 
  theme_bw()
`geom_smooth()` using formula = 'y ~ x'

ggplot(galton_sample, aes(x = scale(father), y = scale(son))) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Regression Line, Standardized Units") +  
  coord_fixed() + 
  theme_bw()
`geom_smooth()` using formula = 'y ~ x'

# Variance explained (R-squared)
print(summary(fit)$r.squared)
[1] 0.1878444

Linear regression improves precision

B <- 1000
N <- 50


results <- galton_sample |>
  rep_slice_sample(reps = B, n = N, replace = TRUE) |>
  summarise(
    # Conditional average with stratification
    ca = mean(son[round(father)==72]), 
    # Linear regression prediction
    lm = predict(lm(son ~ father), newdata = data.frame(father = 72)))

sd(results$ca, na.rm = T)
[1] 1.078234
sd(results$lm, na.rm = T)
[1] 0.5034568

Bivariate normal distribution justification

galton_sample |>
  mutate(father_z = (father-mean(father))/sd(father), 
         father_z_round = round(father_z), 
         son_z = (son - mean(son))/sd(son)) |>
  # Remove outliers
  filter(father_z_round <=2, father_z_round >= -2) |> 
  ggplot() + stat_qq(aes(sample = son_z)) + 
  facet_wrap(~father_z_round, ncol = 5) +
  geom_abline(slope = 1) + 
  coord_fixed() + 
  theme_bw()

© Copyright 2026, Susan Vanderplas

 
  • Report an issue