Week 11: Statistical Modeling & Regression

GPH-GU 2182: Statistical Programming in R · Fall 2026

Yang Feng, PhD

New York University · School of Global Public Health

2026-11-18

Welcome to Week 11!

Today’s Roadmap

  1. Hypothesis Tests: t.test(), prop.test(), chisq.test().
  2. Linear Regression: lm(), coefficients, R-squared.
  3. Logistic Regression: glm(), odds ratios, 95% CIs.
  4. Tidy Models: broom and publication tables.
  5. AI Corner: The negative odds ratio.

Today’s Milestones

  • Homework 11: Released today (modeling & regression).
  • 📝 Quiz 5: Last 30 minutes of class (covers Weeks 9–10).

Cycle 1: Hypothesis Testing

From Describing to Testing

  • Weeks 5–6: group_by() + summarize() describe differences between groups.
  • Today: is a difference bigger than chance would produce?
  • Null hypothesis: no difference in the population.
  • p-value: how surprising our data would be if the null were true. Small (below 0.05) = evidence of a real difference.
  • 95% confidence interval: a range of plausible values for the true difference.

Warning

A p-value is not the size of an effect. Always report the estimate and its CI too.

Today’s Data: NHANES Adults

library(NHANES)

adults <- NHANES |>
  distinct(ID, .keep_all = TRUE) |>   # some people appear twice: keep one row each
  filter(Age >= 20)

nrow(adults)
[1] 4654
  • NHANES: a teaching sample from the US National Health and Nutrition Examination Survey, 2009–2012.
  • We ignore the survey weights, so results describe this sample.

Comparing Two Means: t.test()

bp_test <- t.test(BPSysAve ~ Sex, data = adults)
bp_test

    Welch Two Sample t-test

data:  BPSysAve by Sex
t = -7.8221, df = 4424.5, p-value = 6.452e-15
alternative hypothesis: true difference in means between group female and group male is not equal to 0
95 percent confidence interval:
 -5.097076 -3.054089
sample estimates:
mean in group female   mean in group male 
            119.2834             123.3590 

Reading the t-test

bp_test$estimate
mean in group female   mean in group male 
            119.2834             123.3590 
bp_test$conf.int
[1] -5.097076 -3.054089
attr(,"conf.level")
[1] 0.95
bp_test$p.value
[1] 6.452177e-15
  • Men’s average systolic BP is 4.1 mmHg higher; the 95% CI for the female minus male difference is -5.1 to -3.1 mmHg.
  • The test result is a list (Week 3): pull pieces out with $.

Comparing Two Proportions: Counts First

Have women and men ever smoked (100+ cigarettes in their life) at the same rate?

smoking <- adults |>
  filter(!is.na(Smoke100)) |>
  group_by(Sex) |>
  summarize(smokers = sum(Smoke100 == "Yes"), n = n()) |>
  mutate(share = smokers / n)
smoking
# A tibble: 2 × 4
  Sex    smokers     n share
  <fct>    <int> <int> <dbl>
1 female     890  2396 0.371
2 male      1166  2258 0.516

Comparing Two Proportions: prop.test()

smoke_test <- prop.test(x = smoking$smokers, n = smoking$n)
smoke_test

    2-sample test for equality of proportions with continuity correction

data:  smoking$smokers out of smoking$n
X-squared = 98.431, df = 1, p-value < 2.2e-16
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.1736338 -0.1162338
sample estimates:
   prop 1    prop 2 
0.3714524 0.5163862 
  • x = number with the outcome, n = group size, one entry per group.

Two Categorical Variables: chisq.test()

Is diabetes associated with education level?

edu_diab <- table(adults$Education, adults$Diabetes)
edu_diab
                
                   No  Yes
  8th Grade       275   84
  9 - 11th Grade  537   86
  High School     882  111
  Some College   1259  164
  College Grad   1147   99
chisq.test(edu_diab)

    Pearson's Chi-squared test

data:  edu_diab
X-squared = 67.459, df = 4, p-value = 7.8e-14

Which Test?

Question Outcome Groups Test
Do average BP values differ? numeric 2 t.test(y ~ group, data = ...)
Do two rates differ? yes/no 2 prop.test(x = ..., n = ...)
Are two categories related? categorical 2 or more chisq.test(table(a, b))
  • Each returns a list: $p.value always; $estimate and $conf.int for t.test() and prop.test().
  • With thousands of people, even tiny differences get small p-values: ask whether the size matters.

👥 Paired Exercise 1: Hypothesis Tests (10 min)

Task

  1. Compare total cholesterol (TotChol) between physically active and inactive adults (PhysActive) with t.test().
  2. Count adults with diabetes by Sex, then compare the two shares with prop.test().
  3. Is ever smoking (Smoke100) related to BMI category (BMI_WHO)? Use table() and chisq.test().
  4. Write one plain-language sentence for each p-value.

Checklist

  • Formula: outcome ~ group.
  • Drop missing values before counting.
  • Report the estimate and CI, not only the p-value.

Cycle 2: Linear Regression with lm()

Countries in 2004

gm04 <- gm |>
  filter(year == 2004, !is.na(continent),
         !is.na(life_expectancy), !is.na(sanitation))
nrow(gm04)
[1] 174
  • life_expectancy: years a newborn would live at current death rates.
  • sanitation: percent of people using at least basic sanitation services.

Life Expectancy and Sanitation

ggplot(gm04, aes(sanitation, life_expectancy)) +
  geom_point(alpha = 0.6) +
  geom_smooth(method = "lm", se = FALSE, color = "firebrick") +
  labs(x = "Population using basic sanitation (%)",
       y = "Life expectancy (years)")

Life Expectancy and Sanitation

Fitting a Line with lm()

fit_le <- lm(life_expectancy ~ sanitation, data = gm04)
fit_le

Call:
lm(formula = life_expectancy ~ sanitation, data = gm04)

Coefficients:
(Intercept)   sanitation  
    52.0010       0.2467  
  • Formula: outcome ~ predictor, then data =.
  • Intercept: predicted life expectancy when sanitation is 0% (outside the data, so not meaningful here).
  • Slope: change in predicted life expectancy per 1-point increase in sanitation.

Interpreting the Slope

coef(fit_le)
(Intercept)  sanitation 
 52.0010191   0.2467213 
coef(fit_le)["sanitation"] * 10
sanitation 
  2.467213 
  • Countries with 10 percentage points more sanitation coverage have, on average, a life expectancy about 2.5 years higher.
  • This is an association: richer countries have both better sanitation and better health care.

The Full Report: summary()

summary(fit_le)

Call:
lm(formula = life_expectancy ~ sanitation, data = gm04)

Residuals:
     Min       1Q   Median       3Q      Max 
-16.5342  -2.5415   0.8388   3.4435   9.5700 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 52.00102    0.91901   56.58   <2e-16
sanitation   0.24672    0.01217   20.27   <2e-16

Residual standard error: 5.018 on 172 degrees of freedom
Multiple R-squared:  0.705, Adjusted R-squared:  0.7032 
F-statistic:   411 on 1 and 172 DF,  p-value: < 2.2e-16

R-squared

summary(fit_le)$r.squared
[1] 0.7049635
  • Sanitation alone accounts for about 70% of the country-to-country variation in life expectancy.
  • R-squared runs from 0 (explains nothing) to 1 (explains everything).
  • A high R-squared does not make the relationship causal, and a low one can still be an important effect.

Adding a Categorical Predictor

fit_cont <- lm(life_expectancy ~ sanitation + continent, data = gm04)
coef(fit_cont)
      (Intercept)        sanitation continentAmericas     continentAsia 
       52.2147201         0.1827834         6.9712386         4.8945128 
  continentEurope  continentOceania 
        6.7262907         3.3266092 
  • continent is text, so R creates one coefficient per continent except the first alphabetically: Africa is the reference level.
  • continentEurope: difference from Africa at the same sanitation level.

Choosing the Reference Level

gm04_eu <- gm04 |>
  mutate(continent = fct_relevel(continent, "Europe"))

coef(lm(life_expectancy ~ sanitation + continent, data = gm04_eu))
      (Intercept)        sanitation   continentAfrica continentAmericas 
       58.9410108         0.1827834        -6.7262907         0.2449479 
    continentAsia  continentOceania 
       -1.8317779        -3.3996816 
  • fct_relevel() (forcats, new today; it joins fct_reorder() and fct_lump() from Week 7) moves a level to the front: it becomes the reference.
  • Same model, same fit; the coefficients now compare each continent with Europe.

Several Predictors: Blood Pressure

fit_bp <- lm(BPSysAve ~ Age + Sex, data = adults)
coef(fit_bp)
(Intercept)         Age     Sexmale 
 98.2217221   0.4381471   4.5607888 
  • Age: among people of the same sex, each extra year goes with 0.44 mmHg higher systolic BP.
  • Sexmale: men average 4.6 mmHg higher than women of the same age (female is the reference).
  • lm() drops rows with a missing value in any model variable.

👥 Paired Exercise 2: Linear Regression (10 min)

Task

  1. Fit lm(life_expectancy ~ GDP_per_capita, data = gm04). Interpret the slope (GDP_per_capita is in $1,000 per person).
  2. Compare its R-squared with the sanitation model’s.
  3. Plot the two variables with geom_smooth(method = "lm"). Does a straight line fit well?
  4. Fit BPSysAve ~ Age + Sex + BMI in adults. Interpret the BMI coefficient, then make "male" the reference level with fct_relevel() and refit.

Checklist

  • Coefficient units: outcome units per 1 unit of the predictor.
  • Say “holding the other predictors fixed”.
  • Check which level is the reference.

Cycle 3: Logistic Regression with glm()

Yes/No Outcomes

  • Diabetes (Yes/No), smoking, vaccination: the outcome is a probability.
  • A straight line can predict probabilities below 0 or above 1.
  • Logistic regression models the odds: probability divided by 1 minus probability.
p <- 0.2
p / (1 - p)    # odds: 1 person with the outcome for every 4 without
[1] 0.25

Fitting with glm()

fit_diab <- glm(Diabetes ~ Age + BMI + Sex, family = binomial, data = adults)
coef(fit_diab)
(Intercept)         Age         BMI     Sexmale 
-8.02266444  0.05806330  0.08924975  0.34619255 
levels(adults$Diabetes)
[1] "No"  "Yes"
  • family = binomial makes it a logistic regression.
  • R models the chance of the second level, "Yes".
  • Coefficients are on the log-odds scale: hard to read directly.

From Log Odds to Odds Ratios

exp(coef(fit_diab))
 (Intercept)          Age          BMI      Sexmale 
0.0003279451 1.0597820734 1.0933536899 1.4136747933 
  • Odds ratio (OR): how many times the odds multiply. OR = 1 means no association.
  • Age: each extra year multiplies the odds of diabetes by 1.06, holding BMI and sex fixed.
  • Sexmale: men have 1.41 times the odds of women with the same age and BMI.

95% Confidence Intervals for Odds Ratios

exp(confint(fit_diab))
                   2.5 %      97.5 %
(Intercept) 0.0001693197 0.000620532
Age         1.0532052652 1.066573014
BMI         1.0790685282 1.108015915
Sexmale     1.1625611285 1.720728553
  • Exponentiate the interval endpoints, just like the estimates.
  • An interval that excludes 1 means the association is statistically significant at the 5% level.
  • The male OR’s interval runs from 1.16 to 1.72.

Odds Ratio for a 10-Year Difference

exp(10 * coef(fit_diab)["Age"])
     Age 
1.787169 
  • A one-year OR is close to 1 and easy to undersell.
  • Multiply the coefficient by 10, then exponentiate: someone 10 years older has about 1.8 times the odds of diabetes.

Predicted Probabilities

new_people <- tibble(Age = c(40, 60), BMI = 30, Sex = "male")

predict(fit_diab, newdata = new_people, type = "response")
         1          2 
0.06437752 0.18017215 
  • type = "response" returns probabilities, not log odds.
  • The new data need every predictor in the model, with the same names.

Predicted Risk by Age

grid <- tibble(Age = rep(20:80, times = 2), BMI = 28,
               Sex = rep(c("female", "male"), each = 61))
grid |>
  mutate(prob = predict(fit_diab, newdata = grid, type = "response")) |>
  ggplot(aes(Age, prob, color = Sex)) +
  geom_line(linewidth = 1.2) +
  labs(x = "Age (years)", y = "Predicted probability of diabetes",
       title = "Logistic model, BMI fixed at 28")

Predicted Risk by Age

👥 Paired Exercise 3: Logistic Regression (10 min)

Task

  1. Check levels(adults$Smoke100), then fit glm(Smoke100 ~ Age + Sex + Education, family = binomial, data = adults).
  2. Turn the coefficients into odds ratios with exp(), and get 95% CIs with exp(confint()).
  3. Interpret the ORs for Sexmale and EducationCollege Grad. What is the reference group for each?
  4. Predict the probability of ever smoking for a 30-year-old woman who is a college graduate, and for one with an 8th-grade education.

Checklist

  • family = binomial.
  • exp() the estimates and the CI endpoints.
  • type = "response" for probabilities.

Cycle 4: Tidy Models with broom + AI Corner

Model Output Is Messy

  • coef() gives a named vector, confint() a matrix, summary() a printout.
  • The broom package turns any model into tibbles you can filter(), mutate(), and plot.
Function Returns One row per
tidy() estimates, SEs, p-values, CIs coefficient
glance() R-squared, number of observations, AIC model
augment() fitted values and residuals observation

tidy(): One Row per Coefficient

library(broom)

tidy(fit_bp, conf.int = TRUE)
# A tibble: 3 × 7
  term        estimate std.error statistic   p.value conf.low conf.high
  <chr>          <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
1 (Intercept)   98.2      0.726     135.   0           96.8      99.6  
2 Age            0.438    0.0135     32.5  1.93e-208    0.412     0.465
3 Sexmale        4.56     0.470       9.71 4.72e- 22    3.64      5.48 
  • Columns: estimate, std.error, statistic, p.value, conf.low, conf.high.

tidy() for Logistic Models

tidy(fit_diab, exponentiate = TRUE, conf.int = TRUE)
# A tibble: 4 × 7
  term        estimate std.error statistic   p.value conf.low conf.high
  <chr>          <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
1 (Intercept) 0.000328   0.331      -24.2  1.27e-129 0.000169  0.000621
2 Age         1.06       0.00322     18.1  7.42e- 73 1.05      1.07    
3 BMI         1.09       0.00675     13.2  6.26e- 40 1.08      1.11    
4 Sexmale     1.41       0.1000       3.46 5.36e-  4 1.16      1.72    
  • exponentiate = TRUE turns the estimates and the CI endpoints into odds ratios.
  • The intercept row becomes baseline odds; it is usually dropped from a table.

glance(): One Row per Model

glance(fit_le) |>
  select(r.squared, adj.r.squared, nobs)
# A tibble: 1 × 3
  r.squared adj.r.squared  nobs
      <dbl>         <dbl> <int>
1     0.705         0.703   174
list(sanitation = fit_le, plus_continent = fit_cont) |>
  map_dfr(glance, .id = "model") |>
  select(model, r.squared, adj.r.squared, nobs)
# A tibble: 2 × 4
  model          r.squared adj.r.squared  nobs
  <chr>              <dbl>         <dbl> <int>
1 sanitation         0.705         0.703   174
2 plus_continent     0.753         0.746   174
  • map_dfr() (Week 9) stacks one row per model: easy side-by-side comparison.

augment(): One Row per Observation

le_aug <- augment(fit_le)

le_aug |>
  select(life_expectancy, sanitation, .fitted, .resid)
# A tibble: 174 × 4
  life_expectancy sanitation .fitted .resid
            <dbl>      <dbl>   <dbl>  <dbl>
1            76.2       92.3    74.8  1.43 
2            69.2       97.4    76.0 -6.83 
3            75.3       89.9    74.2  1.12 
4            73         88.9    73.9 -0.935
5            81.2      100      76.7  4.53 
# ℹ 169 more rows
  • .fitted: the model’s prediction. .resid: observed minus predicted.

Checking the Fit with Residuals

  • A few countries sit far below their prediction: something besides sanitation matters there.

Building a Publication Table

or_table <- tidy(fit_diab, exponentiate = TRUE, conf.int = TRUE) |>
  filter(term != "(Intercept)") |>
  mutate(Predictor = case_when(term == "Age" ~ "Age (per year)",
                               term == "BMI" ~ "BMI (per 1 kg/m2)",
                               term == "Sexmale" ~ "Male (vs. female)"),
         p = ifelse(p.value < 0.001, "< 0.001", format(round(p.value, 3), nsmall = 3))) |>
  select(Predictor, OR = estimate, `CI low` = conf.low, `CI high` = conf.high, p)
  • Readable labels, no intercept, rounded p-values. Next: print it with knitr::kable().

The Table

knitr::kable(or_table, digits = 2,
             caption = "Odds ratios for diabetes, NHANES adults")
Odds ratios for diabetes, NHANES adults
Predictor OR CI low CI high p
Age (per year) 1.06 1.05 1.07 < 0.001
BMI (per 1 kg/m2) 1.09 1.08 1.11 < 0.001
Male (vs. female) 1.41 1.16 1.72 < 0.001
  • Next week: richer tables with gt.

AI Corner: The Negative Odds Ratio

Asked to “estimate the odds ratio of diabetes for physically active versus inactive adults, adjusting for age,” an AI wrote:

fit_ai <- glm(Diabetes ~ PhysActive + Age, family = binomial, data = adults)

tidy(fit_ai, conf.int = TRUE) |>
  filter(term == "PhysActiveYes") |>
  select(term, estimate, conf.low, conf.high)
# A tibble: 1 × 4
  term          estimate conf.low conf.high
  <chr>            <dbl>    <dbl>     <dbl>
1 PhysActiveYes   -0.388   -0.584    -0.194

AI’s write-up: “The odds ratio for physical activity is -0.39, so active adults have 39% lower odds of diabetes.”

The code runs and the sentence sounds right. Ship it?

AI Corner: Auditing the Odds Ratio

Audit findings:

levels(adults$PhysActive)
[1] "No"  "Yes"
exp(coef(fit_ai)["PhysActiveYes"])
PhysActiveYes 
     0.678412 
  1. tidy() without exponentiate = TRUE reports log odds. An odds ratio can never be negative.
  2. “39% lower” read the log odds as a percentage. The real OR is 0.68: about 32% lower odds.
  3. The reference level checks out: "No" comes first, so the comparison is active versus inactive.

AI Corner: The Audited Version

tidy(fit_ai, exponentiate = TRUE,
     conf.int = TRUE) |>
  filter(term == "PhysActiveYes") |>
  select(term, estimate,
         conf.low, conf.high)
# A tibble: 1 × 4
  term          estimate conf.low conf.high
  <chr>            <dbl>    <dbl>     <dbl>
1 PhysActiveYes    0.678    0.558     0.823
  • Estimate and CI endpoints are on the odds-ratio scale.
  • Sanity checks: ORs are positive; the CI contains the estimate; the reference level is the one you meant.

Important

Logistic coefficients are log odds. Exponentiate before you call them odds ratios.

👥 Paired Exercise 4: broom + AI Audit (10 min)

Task

  1. Fit BPSysAve ~ Age + Sex and BPSysAve ~ Age + Sex + BMI; compare them with glance() and map_dfr().
  2. augment() your GDP model from Exercise 2 and plot .resid against .fitted. What pattern do you see?
  3. Make a publication table of odds ratios for your Exercise 3 smoking model with tidy() and knitr::kable().
  4. Audit the AI code in the worksheet: find the flaw and fix it.

Checklist

  • tidy(..., exponentiate = TRUE, conf.int = TRUE) for logistic models.
  • Drop the intercept from an OR table.
  • Check the reference level.

📝 Quiz 5 (Last 30 Minutes)

  • Coverage: Weeks 9–10 (writing functions, stopifnot(), map() and map_*(), sample() and set.seed(), the d/p/q/r functions, Monte Carlo simulation, the Central Limit Theorem).
  • Format: Paper-based, closed-book, no electronic devices.
  • Length: 20 minutes, multiple choice.

Note

Laptops closed, please. Your in-class worksheet should already be pushed to GitHub before the quiz begins.

Wrap-Up & Next Steps

Before We Meet Again

📌 To Do This Week

  • Homework 11 (modeling & regression): due date on the course website.
  • Read: R02Pro Ch 14 (advanced Quarto).
  • Push today’s worksheet to GitHub.
  • 🎯 Final project: keep going; instructions and milestones are on the course website.

🔭 Next Week

  • Advanced Quarto: parameterized reports.
  • Publication tables with gt and interactive tables with DT.
  • Today’s models feed straight into those tables.

Questions? Office hours are listed on the syllabus page, or email anytime.