clinic_a$bmi <- clinic_a$weight / clinic_a$height^2
clinic_b$bmi <- clinic_b$weight / clinic_b$height^2
clinic_c$bmi <- clinic_c$weight / clinic_a$height^2 # spot the bug?GPH-GU 2182: Statistical Programming in R · Fall 2026
New York University · School of Global Public Health
2026-11-04
function(), arguments, return values.purrr::map() and friends.map() over groups.Three clinics, three copies of the same line:
If the body uses vectorized operations, so does your function:
[1] 21.48437 22.85714 28.39506
ifelse() and case_when() work inside functions the same way.mutate()A vectorized function drops straight into mutate():
[1] "underweight" "healthy" "overweight" "obese" NA
TRUE ~ ... line, so a missing BMI stays NA instead of becoming "obese".bmi_category(bmi(weights, heights)).return()[1] 2.5
[1] NA
return() stops the function immediately: use it for early exits.f_to_c(temp_f) returning (temp_f - 32) * 5 / 9. Test it on 98.6 and 104.temps_f in your worksheet.fever_flag(temp_c) returning "fever" when temp_c >= 38, else "no fever" (use ifelse()).mutate() on the patients tibble: fever_flag(f_to_c(temp_f)).[1] 20.83333
[1] 0.2083333
per = 1000).[1] 20.83333
[1] 4.8e+08
[1] FALSE FALSE TRUE
[1] FALSE TRUE TRUE
R looks for a name inside the function first, then in the environment where the function was defined.
[1] 25
[1] 0
total <- add_cases(25).stopifnot()Error in `rate_per()`:
! all(population > 0) is not TRUE
Error in `rate_per()`:
! is.numeric(cases) is not TRUE
TRUE stops the function with an error.stop()Error in `bmi()`:
! height_m looks like centimeters; divide by 100 first
Tip
A loud error that says how to fix it beats a silent BMI of 0.0023 that flows into your paper.
incidence_rate(cases, population, per = 100000).mutate() on the counties tibble in your worksheet; then again with per = 1000.stopifnot() checks: population must be positive and cases cannot exceed population.bad_counties and read the error. Then replace the checks with if + stop() messages a colleague would understand.for Loop to map()map() Always Returns a Listmap(.x, .f) applies .f to each element of .x:
When each result is a single value, a typed variant returns a vector instead of a list.
map_dbl(), map_int(), map_lgl(), map_chr()brooklyn queens bronx
139.0000 126.3333 148.6000
brooklyn queens bronx
4 3 5
The suffix is a promise about the output type, and purrr enforces it:
For one-off logic, write the function right inside map():
brooklyn queens bronx
0.5 0.0 0.8
brooklyn queens bronx
FALSE FALSE TRUE
\(x) ... is shorthand for function(x) ....~ mean(.x >= 140): same idea, older syntax.So map() over a data frame visits each column:
life_expectancy child_mortality GDP_per_capita
41 39 34
life_expectancy child_mortality GDP_per_capita
72.100 20.900 5.125
map() (10 min)Your worksheet provides site_waits, a named list of wait times (minutes) at four sites.
for loop computing each site’s median wait (na.rm = TRUE).map_dbl() and confirm the results are identical.map_lgl() to flag sites where any wait exceeds 60 minutes.map_int() to count waits over 60 minutes at each site.map_dbl() for one number per element, map_lgl() for one TRUE/FALSE.all.equal().# A tibble: 1 × 3
continent n_countries median_le
<chr> <int> <dbl>
1 Asia 46 71.7
map() + list_rbind(): One Row per GroupLast week’s loop printed one line per continent. Now we get a table back:
# A tibble: 5 × 3
continent n_countries median_le
<chr> <int> <dbl>
1 Africa 50 60.2
2 Americas 36 74.6
3 Asia 46 71.7
4 Europe 38 79.3
5 Oceania 12 65.8
list_rbind() stacks a list of data frames (older code uses map_dfr()).group_by() + summarize() does this particular job too; map() shines when the per-group step is not a dplyr verb (one plot, one model, or one file per group).map()?Use a for / while loop when… |
Use map_*() when… |
|---|---|
each step depends on the previous one (running totals, while) |
each element is handled independently |
| the point is a side effect (printing, saving files) | the point is the returned values |
| you are fine pre-allocating output yourself | you want output allocated and type-checked for you |
Both are correct R; map() is usually shorter and harder to get wrong.
Asked for “the share of countries with life expectancy at or above a cutoff,” an AI wrote:
[1] 0.3230769
It runs, handles NA, and the number looks plausible. Ship it?
Audit findings:
df from the global environment. Reuse the name later and the same call silently gives a different answer:life_expectancy: useless for any other variable.cutoff is a single number.[1] 0.3230769
[1] 0.8410256 0.5846154 0.1435897
x, so the function works for any year and any variable.stopifnot() rejects a bad cutoff before any work happens.map_dbl() reuses it across cutoffs in one line.Important
Everything a function uses should arrive through its arguments.
if/else, ifelse(), case_when(), for and while loops).Note
Laptops closed, please. Your in-class worksheet should already be pushed to GitHub before the quiz begins.
map() will run thousands of simulated studies.Questions? Office hours are listed on the syllabus page, or email anytime.