Session 8: Programming — Functions, if/else, Loops, and Iteration

Writing functions, if/else and if_else(), for loops, and iteration with map() and walk()

NoteIn this session you will learn to

This session is optional / advanced: it builds on everything before it, especially vectors and subsetting (Session 4) and plotting (Sessions 6 and 7).

  1. Write your own functions with arguments and default values
  2. Write functions that work on data frames and return tables or plots
  3. Use if/else for one value and if_else() for a whole column, and explain the difference
  4. Repeat a task with a for loop — for example, saving one epidemic curve per hospital
  5. Do the same with map() / walk() from purrr (part of the tidyverse)

Before you start: open the workshop folder in Positron (File → Open Folder…) and open student_scripts/Session 8 - Programming_STUDENT.R. This session starts from processed_data/combined_linelist.rds and processed_data/measles_final.rds, which you saved in Session 3. If you missed it, ready-made copies are already in processed_data/.

Today’s goal: “Your manager wants an epidemic curve for every hospital, every week.” By the end of the session, one loop does it.

Where this session fits. Most data projects go through the same steps, whatever the topic. This session covers the last one, Automate (highlighted): turning steps you repeat into functions and loops, so one line of code redoes the whole job, for example next week’s epidemic curves.

  1. Import
  2. Inspect
  3. Clean
  4. Combine
  5. Reshape
  6. Summarize
  7. Visualize
  8. Save and share
  9. Automate

Part 1: Set up

library(tidyverse)
library(here)
library(rio)
library(janitor)

linelist <- import(here("processed_data", "combined_linelist.rds"), trust = TRUE)
Note🔍 What this code does
  • The four library() lines load today’s packages: the tidyverse (which includes purrr, with map() and walk() for Part 6), here, rio, and janitor (for make_clean_names() in Part 5).
  • import() reads combined_linelist.rds, the file you saved in Session 3: 6451 rows and 19 columns.
  • trust = TRUE says you trust where the .rds file came from. An .rds file can hold more than plain data, so rio asks you to confirm.
Important✏️ TRY IT 1 (1 min): import the measles data

Import processed_data/measles_final.rds as measles.

✅ Check: in the Variables pane, measles shows 1163 rows and 14 columns

measles <- import(here("processed_data", "measles_final.rds"), trust = TRUE)
dim(measles)
[1] 1163   14

measles appears in the Variables pane with 1163 rows and 14 columns.

Part 2: Writing your first function

Why write functions?

If you copy and paste code more than twice, write a function. Functions:

  • avoid copy-paste mistakes (change it once, fixed everywhere)
  • give a task a clear name (c_to_f() says what it does)
  • make your scripts shorter and easier to read

The shape of a function

c_to_f <- function(temp_c) {
  temp_c * 9 / 5 + 32
}
  • c_to_f is the name — you save a function with <- like any object. Run the whole block to create it; then it appears in the Variables pane
  • temp_c is the argument — the input. Inside the function, it is whatever value you pass in
  • The code between { } is the body
  • The function returns the result of its last line
c_to_f(38)
[1] 100.4
c_to_f(c(36.8, 38.5, 40.1))   # it's vectorized, because the maths inside is
[1]  98.24 101.30 104.18
Note🔍 What this code does
  • c_to_f(38) runs the body with temp_c set to 38: 38 × 9 / 5 + 32 = 100.4.
  • c_to_f(c(36.8, 38.5, 40.1)) converts all three at once: 98.24, 101.3, and 104.18. You didn’t write a loop: *, /, and + already work on every value in a vector, so your function does too.
  • temp_c only exists while the function runs. It doesn’t appear in the Variables pane.

Because it’s vectorized, it works on a whole column inside mutate():

linelist %>%
  mutate(temp_f = c_to_f(temp)) %>%
  select(case_id, temp, temp_f) %>%
  head(3)
  case_id temp temp_f
1  5fe599 36.8  98.24
2  8689b7 36.9  98.42
3  11f8ea 36.9  98.42
Note🔍 What this code does
  • mutate(temp_f = c_to_f(temp)) gives the whole temp column to c_to_f() and stores the answers in a new column, temp_f. 36.8 °C becomes 98.24 °F.
  • select() and head(3) just keep the output short. linelist itself doesn’t change, because the result isn’t saved with <-.

Default values

Give an argument a default with =. You can change it, but you don’t have to:

c_to_f <- function(temp_c, digits = 1) {
  round(temp_c * 9 / 5 + 32, digits)
}

c_to_f(38.37)              # uses digits = 1
[1] 101.1
c_to_f(38.37, digits = 0)  # overrides it
[1] 101
Note🔍 What this code does
  • This new c_to_f() replaces the old one, because it’s saved under the same name.
  • digits = 1 inside function() sets a default. c_to_f(38.37) doesn’t mention digits, so it uses 1 and gives 101.1.
  • c_to_f(38.37, digits = 0) overrides the default and rounds to a whole number: 101.
  • Inside the body, round(..., digits) passes your choice on to round().
WarningCommon mistakes
  • Changing the function but not re-running the block: R still uses the old version.
Important✏️ TRY IT 2 (4 min): Fahrenheit to Celsius

Write f_to_c(temp_f) that converts Fahrenheit to Celsius: (temp_f - 32) * 5 / 9, rounded to 1 decimal. Test it on 98.6 and 104.7.

✅ Check: f_to_c(98.6) is 37 and f_to_c(104.7) is 40.4

f_to_c <- function(temp_f) {
  round((temp_f - 32) * 5 / 9, 1)
}

f_to_c(98.6)
[1] 37
f_to_c(104.7)
[1] 40.4

104.7 °F is 40.4 °C — the Fahrenheit temperature you found in the measles data in Session 1!

Note📖 Good to know
  • Functions you write live in R’s memory, like any object. They’re gone when R restarts, so keep them in your script, near the top, and run them before you use them.
  • Give functions names that say what they do, such as make_epicurve() or c_to_f(). Avoid names that R already uses, like mean or c: your version would hide the original.
  • In other people’s code you may see return(x). It ends the function and gives back x. Without it, the function returns its last line. Both are fine.

Part 3: Functions that use data

A calculation used in many places

pct <- function(x, digits = 1) {
  round(mean(x, na.rm = TRUE) * 100, digits)
}

linelist %>%
  group_by(hospital_name) %>%
  summarise(
    n         = n(),
    pct_death = pct(outcome == "Death"),
    pct_fever = pct(fever == "yes")
  )
# A tibble: 7 × 4
  hospital_name                     n pct_death pct_fever
  <chr>                         <int>     <dbl>     <dbl>
1 Central Hospital                454      42.5      77.3
2 HMO Health                      280      44.3      92.9
3 Military Hospital               896      44.5      79  
4 Other/Unknown                  2354      42.7      77.3
5 Premiere Health                 274      47.1      94.5
6 Regional Medical center        1771      44.6      76.7
7 St. Mark's Maternity Hospital   422      47.2      75.8

Compare with Session 5, where we wrote round(mean(...) * 100, 1) every time.

Note🔍 What this code does
  • pct() expects a vector of TRUE and FALSE. The mean() of TRUE/FALSE values is the share that are TRUE (TRUE counts as 1, FALSE as 0). * 100 makes it a percentage, and na.rm = TRUE skips missing values.
  • outcome == "Death" is TRUE for every patient who died, so pct(outcome == "Death") is the percentage who died: 44.5% at Military Hospital.
  • group_by(hospital_name) makes summarise() do this once per hospital, giving 7 rows (including Other/Unknown).

A function that takes a data frame

hospital_summary <- function(data, hospital) {
  data %>%
    filter(hospital_name == hospital) %>%
    summarise(
      n         = n(),
      pct_death = pct(outcome == "Death")
    )
}

hospital_summary(linelist, "Military Hospital")
    n pct_death
1 896      44.5
hospital_summary(linelist, "Central Hospital")
    n pct_death
1 454      42.5

hospital is an argument holding a value (the hospital’s name), so it can go straight into filter().

Note🔍 What this code does
  • hospital_summary() takes two arguments: the data, and the name of one hospital.
  • Inside, filter(hospital_name == hospital) keeps that hospital’s rows. summarise() then counts them and works out the death percentage with your own pct() function. A function can use other functions you wrote, as long as you’ve run them first.
  • Same function, different input: Military Hospital has 896 cases (44.5% died) and Central Hospital has 454 (42.5%).

A function that makes a plot

make_epicurve <- function(data, hospital) {
  data %>%
    filter(hospital_name == hospital, onset_date >= as.Date("2014-01-01")) %>%
    ggplot(aes(x = onset_date)) +
    geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white") +
    labs(
      title = paste("Weekly cases:", hospital),
      x     = "Week of onset",
      y     = "Number of cases"
    ) +
    theme_minimal()
}

make_epicurve(linelist, "Military Hospital")

Epidemic curve titled Weekly cases: Military Hospital, from April 2014 to April 2015, peaking at about 50 cases in one week in autumn 2014.

paste("Weekly cases:", hospital) builds the title from the argument, so every plot gets the right title.

Note🔍 What this code does
  • The body is an ordinary plot pipeline. filter() keeps one hospital, and geom_histogram(binwidth = 7) puts each week’s cases into one bar.
  • onset_date >= as.Date("2014-01-01") also drops onset dates before 2014, which would stretch the time axis back to 2012.
  • A function returns its last value, and here that’s the plot, so make_epicurve(linelist, "Military Hospital") draws it. You could also save it first: p <- make_epicurve(linelist, "Military Hospital").
WarningCommon mistake: name the argument district_name, not district

Don’t give an argument the same name as a column! In

function(data, district) { data %>% filter(district == district) }

R compares the district column with itself, so every row is kept — no error, just the wrong answer. Name the argument district_name instead: filter(district == district_name).

Important✏️ TRY IT 3 (6 min): measles functions
  1. Write rate_per_10k(cases, population) that returns cases / population * 10000, rounded to 1 decimal. Use it in mutate() after count(district, population).
  2. Write district_summary(data, district_name) that returns the number of cases and the percentage vaccinated (use your pct() function!) for one district.

✅ Check: a) East is 22.8 b) district_summary(measles, "North") gives n 342, 25.7%

# a)
rate_per_10k <- function(cases, population) {
  round(cases / population * 10000, 1)
}

measles %>%
  count(district, population) %>%
  mutate(rate = rate_per_10k(n, population)) %>%
  arrange(desc(rate))
  district population   n rate
1     East      98000 223 22.8
2     West      76500 170 22.2
3    South     142000 284 20.0
4    North     185000 342 18.5
5  Central     210000 110  5.2
6  Unknown         NA  34   NA
# b)
district_summary <- function(data, district_name) {
  data %>%
    filter(district == district_name) %>%
    summarise(
      n              = n(),
      pct_vaccinated = pct(vaccinated == "Yes")
    )
}

district_summary(measles, "North")
    n pct_vaccinated
1 342           25.7

East has the highest rate, 22.8 cases per 10,000. North has 342 cases, and 25.7% of them were vaccinated. Because the argument is called district_name, filter(district == district_name) keeps only North.

Part 4: if / else

if runs code only when a condition is TRUE. else runs when it’s FALSE:

fever_status <- function(temp) {
  if (temp >= 38) {
    "fever"
  } else {
    "no fever"
  }
}

fever_status(39.2)
[1] "fever"
fever_status(36.9)
[1] "no fever"
Note🔍 What this code does
  • if (temp >= 38) asks one yes/no question. When the answer is TRUE, R runs the code in the first { } and returns “fever”. When it’s FALSE, R runs the else { } part and returns “no fever”.
  • 39.2 is at least 38, so it’s “fever”. 36.9 isn’t, so it’s “no fever”.

if works on ONE value

fever_status(c(39.2, 36.9))
Error in `if (temp >= 38) ...`:
! the condition has length > 1
Note🔍 What this code does
  • With two temperatures, temp >= 38 gives two answers (TRUE, FALSE), but if can only take one. R stops with “the condition has length > 1”.
  • This error is on purpose: it shows that if handles one value at a time.

if asks one yes/no question. For a whole column, use the vectorized if_else() from Session 2:

fever_status <- function(temp) {
  if_else(temp >= 38, "fever", "no fever")
}

fever_status(c(39.2, 36.9))
[1] "fever"    "no fever"
linelist %>%
  mutate(fever_measured = fever_status(temp)) %>%
  count(fever_measured)
  fever_measured    n
1          fever 4976
2       no fever 1324
3           <NA>  151
Note🔍 What this code does
  • if_else(temp >= 38, "fever", "no fever") checks every value and picks an answer for each, so this fever_status() works on a whole vector: 39.2 and 36.9 give “fever” and “no fever”.
  • In mutate(), it runs on the whole temp column: 4976 “fever”, 1324 “no fever”, and 151 NA where the temperature is missing. if_else() keeps missing values missing.
  • This version replaces the one-value version, because it has the same name.

Where if shines: checking inputs

if is perfect for questions with one answer, like “is the input a number?”. stop() ends the function with a helpful error message:

c_to_f <- function(temp_c, digits = 1) {
  if (!is.numeric(temp_c)) {
    stop("temp_c must be a number, not ", class(temp_c))
  }
  round(temp_c * 9 / 5 + 32, digits)
}

c_to_f("38")
Error in `c_to_f()`:
! temp_c must be a number, not character
Note🔍 What this code does
  • is.numeric(temp_c) asks “is this a number?”. The ! turns the answer around, so the if is TRUE when the input is not a number.
  • stop() then ends the function straight away with your message. class(temp_c) adds the type that was given: “temp_c must be a number, not character”.
  • "38" is in quotes, so it’s text, and the function stops before doing any maths. Without the check, R would give a less helpful error: “non-numeric argument to binary operator”.
Important✏️ TRY IT 4 (5 min): fever status for the measles data
  1. Write a one-value fever_status() with if / else and test it on 38.5.
  2. Write the vectorized version with if_else(), use it in mutate() on measles$temp_c, and count() the result.

✅ Check: a) "fever" b) 1015 “fever” and 148 “no fever”

# a)
fever_status_one <- function(temp) {
  if (temp >= 38) {
    "fever"
  } else {
    "no fever"
  }
}

fever_status_one(38.5)
[1] "fever"
# b)
fever_status <- function(temp) {
  if_else(temp >= 38, "fever", "no fever")
}

measles %>%
  mutate(fever_measured = fever_status(temp_c)) %>%
  count(fever_measured)
  fever_measured    n
1          fever 1015
2       no fever  148

38.5 is at least 38, so the one-value version returns "fever". The if_else() version works on all 1163 temperatures at once: 1015 with fever and 148 without.

Note📖 Good to know
  • if needs exactly one TRUE or FALSE, so a missing value fails too: if (NA) gives “missing value where TRUE/FALSE needed”. When a value might be missing, check it first with is.na().
  • else if (...) checks another condition when the first one is FALSE, like the lines of a case_when() for a single value.

Part 5: for loops

A for loop runs the same code once for each value in a vector:

for (h in c("Central Hospital", "Military Hospital")) {
  print(h)
}
[1] "Central Hospital"
[1] "Military Hospital"

Read it as: “for each h in this vector, run the code between { }”. h takes each value in turn.

Note🔍 What this code does
  • The first time through, h is “Central Hospital”; the second time, “Military Hospital”. Then the loop ends.
  • print(h) shows the current value. You can call the loop variable anything; h is short for hospital.

Loop over every hospital

hospitals <- linelist %>%
  filter(hospital_name != "Other/Unknown") %>%
  distinct(hospital_name) %>%
  pull(hospital_name) %>%
  sort()

hospitals
[1] "Central Hospital"              "HMO Health"                   
[3] "Military Hospital"             "Premiere Health"              
[5] "Regional Medical center"       "St. Mark's Maternity Hospital"
for (h in hospitals) {
  n_cases <- sum(linelist$hospital_name == h)
  print(paste(h, "has", n_cases, "cases"))
}
[1] "Central Hospital has 454 cases"
[1] "HMO Health has 280 cases"
[1] "Military Hospital has 896 cases"
[1] "Premiere Health has 274 cases"
[1] "Regional Medical center has 1771 cases"
[1] "St. Mark's Maternity Hospital has 422 cases"

Inside a loop, results are not printed automatically — use print().

Note🔍 What this code does
  • The pipeline makes a vector of the six hospital names: filter() drops “Other/Unknown”, distinct() keeps each name once, pull() turns the column into a plain vector, and sort() puts it in alphabetical order.
  • In the loop, linelist$hospital_name == h is TRUE for each case at hospital h, and sum() counts the TRUEs.
  • paste() joins the pieces into a sentence with spaces between them, and print() shows it: “Central Hospital has 454 cases”.

Save the results

To keep results, create an empty container before the loop and fill it inside:

case_counts <- c()   # an empty vector

for (h in hospitals) {
  case_counts[h] <- sum(linelist$hospital_name == h)
}

case_counts
             Central Hospital                    HMO Health 
                          454                           280 
            Military Hospital               Premiere Health 
                          896                           274 
      Regional Medical center St. Mark's Maternity Hospital 
                         1771                           422 
Note🔍 What this code does
  • case_counts <- c() makes an empty vector before the loop.
  • Each time through, case_counts[h] <- ... adds one count, labelled with the hospital’s name.
  • After the loop, case_counts holds all six counts, from Central Hospital (454) to St. Mark’s Maternity Hospital (422). Unlike printed output, you can keep using them.

The payoff: one epidemic curve per hospital

for (h in hospitals) {
  p <- make_epicurve(linelist, h)
  file_name <- paste0("epicurve_", make_clean_names(h), ".png")
  ggsave(here("outputs", file_name), plot = p, width = 8, height = 5, dpi = 300)
}
  • make_clean_names() (janitor) turns “St. Mark’s Maternity Hospital” into st_marks_maternity_hospital — safe for a file name
  • paste0() glues the pieces with no spaces into epicurve_st_marks_maternity_hospital.png
  • Six files, one loop. Next week, re-run it with the new data — check the Explorer to see the new files in outputs/
Note🔍 What this code does
  • Each time through, p <- make_epicurve(linelist, h) makes that hospital’s plot and stores it in p.
  • ggsave() saves p in outputs/ under the new file name, as an 8 × 5 inch image at 300 dpi (print quality).
NoteYou’ve already been looping

mutate(), summarise() with group_by(), and across() all repeat work for you. In R, reach for those first; write a loop when you need to repeat a whole task, like making and saving a plot.

Important✏️ TRY IT 5 (6 min): one epicurve per district

Write make_measles_epicurve(data, district_name) for weekly cases by report_date in one district. Then loop over the five districts (not “Unknown”) and save each plot to outputs/ as measles_central.png, measles_east.png, …

✅ Check: five new .png files in the outputs folder

make_measles_epicurve <- function(data, district_name) {
  data %>%
    filter(district == district_name, !is.na(report_date)) %>%
    ggplot(aes(x = report_date)) +
    geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white") +
    labs(
      title = paste("Weekly measles cases:", district_name),
      x     = "Week of report",
      y     = "Number of cases"
    ) +
    theme_minimal()
}

districts <- c("Central", "East", "North", "South", "West")

for (d in districts) {
  p <- make_measles_epicurve(measles, d)
  file_name <- paste0("measles_", make_clean_names(d), ".png")
  ggsave(here("outputs", file_name), plot = p, width = 8, height = 5, dpi = 300)
}

The loop creates five files in outputs/: measles_central.png, measles_east.png, measles_north.png, measles_south.png, and measles_west.png. Again, the argument is district_name, not district.

Note📖 Good to know
  • Fixing a loop that goes wrong: set the loop variable by hand, for example h <- hospitals[1], then run the lines inside the loop one at a time. You’ll see exactly where it breaks.
  • After the loop, the loop variable keeps its last value: here, h is “St. Mark’s Maternity Hospital”.
  • To loop over positions (1, 2, 3, …) instead of values, use for (i in seq_along(hospitals)), then hospitals[i] inside the loop.

Part 6: Iteration the tidyverse way: map() and walk()

The purrr package (part of the tidyverse) does what loops do, in one line:

  • map(x, f) — run f on each element of x and return a list of results
  • map_dbl() — the same, but return a number vector
  • walk(x, f) — run f on each element for its side effect (like saving a file), return nothing
# The mean of three columns
linelist %>%
  select(age_years, bmi, temp) %>%
  map_dbl(~ mean(.x, na.rm = TRUE))
age_years       bmi      temp 
 16.05732  30.59385  38.58784 

A data frame is a list of columns, so map_dbl() runs once per column. ~ mean(.x, na.rm = TRUE) is a short function: .x is the current element — the same ~ .x you used with across() in Session 3.

Note🔍 What this code does
  • select() keeps three columns. map_dbl() then runs mean(.x, na.rm = TRUE) on each one, with .x standing for the current column.
  • The result is a number vector with one named value per column: a mean age of about 16.1 years, a mean BMI of about 30.6, and a mean temperature of about 38.6 °C.
# A list of six plots
epicurves <- map(hospitals, ~ make_epicurve(linelist, .x))
length(epicurves)
[1] 6
epicurves[[1]]

Epidemic curve titled Weekly cases: Central Hospital, the first plot in the list made by map(), peaking at about 28 cases in one week in autumn 2014.

Tip🧩 Reading a function call

Here is the map() line you just ran, taken apart:

epicurves <- map(hospitals, ~ make_epicurve(linelist, .x))

Piece What it is What it does
epicurves the name of a new object holds the result
<- the assignment arrow saves the result in epicurves
map(...) a function from the purrr package runs a function once for each element, and returns a list
hospitals the first argument of map() the vector to go through: six hospital names
~ make_epicurve(linelist, .x) the second argument: a short, nameless function what to do with each element
.x a placeholder the current hospital name, a different one each time

map() takes the first hospital, puts it in .x, runs make_epicurve(linelist, "Central Hospital"), and keeps the plot. Then it does the same for the next hospital, and so on. Read it aloud as: “for each of the hospitals, make an epicurve, and collect them in epicurves.”

Note🔍 What this code does
  • map() runs make_epicurve(linelist, .x) six times, once per hospital, and collects the six plots in a list called epicurves.
  • length(epicurves) is 6. epicurves[[1]] takes the first plot (Central Hospital) out of the list and draws it. [[ ]] pulls one element out of a list, as in Session 4.
# Save them all: the same as the for loop in Part 5, in one call
walk(hospitals, ~ ggsave(
  here("outputs", paste0("epicurve_", make_clean_names(.x), ".png")),
  plot = make_epicurve(linelist, .x), width = 8, height = 5, dpi = 300
))
Note🔍 What this code does
  • walk() goes through hospitals like map(), but keeps nothing. It’s for work you do for its effect, like saving files.
  • For each hospital .x, ggsave() makes the plot and saves it under the same file name as the Part 5 loop, so you get the same six files.
NoteLoop or map()?

Both are fine! Loops are easier to read when you’re starting out; map() is shorter and is what you’ll see in modern R code. Choose the one you can read.

Note🔁 The base R way: lapply() and sapply()

Base R’s apply family does the same job, and you will see it everywhere in older code, help pages, and bioinformatics packages (Bioconductor):

purrr base R returns
map(x, f) lapply(x, f) a list
map_dbl(x, f) sapply(x, f) (or vapply(x, f, numeric(1))) a vector, usually
three_cols <- linelist[, c("age_years", "bmi", "temp")]

sapply(three_cols, mean, na.rm = TRUE)    # like map_dbl()
age_years       bmi      temp 
 16.05732  30.59385  38.58784 
lapply(three_cols, range, na.rm = TRUE)   # like map(): a list
$age_years
[1]  0 84

$bmi
[1] 10.9 60.0

$temp
[1] 35.2 40.8
sapply(three_cols, range, na.rm = TRUE)   # surprise: a matrix!
     age_years  bmi temp
[1,]         0 10.9 35.2
[2,]        84 60.0 40.8
Note🔍 What this code does
  • linelist[, c("age_years", "bmi", "temp")] keeps three columns with base R subsetting: all rows (nothing before the comma), these columns.
  • sapply(three_cols, mean, na.rm = TRUE) gives one number per column, the same as map_dbl(). mean has no brackets, because you hand over the function itself instead of running it.
  • lapply(three_cols, range, na.rm = TRUE) gives a list with two numbers (smallest and largest) per column: for example, ages run from 0 to 84.
  • sapply(three_cols, range, na.rm = TRUE) also gets two numbers per column, so it quietly builds a matrix with 2 rows and 3 columns.

Extra arguments (na.rm = TRUE) go after the function name. sapply() guesses the shape of the result: a vector, a matrix, or a list. That guessing is why purrr has map_dbl(), map_chr(), and friends, which always return the type their name says. For your own functions, the base R shorthand is \(x) mean(x, na.rm = TRUE), the same idea as ~ mean(.x, na.rm = TRUE).

Important✏️ TRY IT 6 (5 min): map and walk
  1. Use map_dbl() to find the mean of age_years, temp_c, and days_in_hospital in measles.
  2. Replace your district loop with walk().

✅ Check: a) 8.75, 38.82, 4.94 b) the same five .png files

# a)
measles %>%
  select(age_years, temp_c, days_in_hospital) %>%
  map_dbl(~ mean(.x, na.rm = TRUE))
       age_years           temp_c days_in_hospital 
        8.749559        38.818659         4.936768 
# b)
walk(districts, ~ ggsave(
  here("outputs", paste0("measles_", make_clean_names(.x), ".png")),
  plot = make_measles_epicurve(measles, .x), width = 8, height = 5, dpi = 300
))
  1. The mean age is 8.75 years, the mean temperature 38.82 °C, and the mean hospital stay 4.94 days (na.rm = TRUE skips patients who were never hospitalized). b) walk() saves the same five files as your loop: measles_central.png, measles_east.png, measles_north.png, measles_south.png, and measles_west.png.
Tip⭐ Bonus
  1. Add a fill argument to make_epicurve(), with a default of "#2a78d6", so you can choose the bar color.
  2. Add an input check to rate_per_10k(): stop() if population is 0 or missing.
  3. Write a function that makes the whole measles Table 1 from Session 5, and run it for each district with map().
  4. Brought your own data? Find a piece of code you copied and pasted, and turn it into a function.

See the solutions file for answers.

Key points

  • Write it once, run it many times: if you copy and paste code more than twice, write a function with function().
  • A function takes arguments (which can have default values) and returns the result of its last line. Re-run the block after every change.
  • Never give an argument the same name as a column — use district_name, not district.
  • if / else works on one value (great for input checks with stop()); if_else() works on a whole column.
  • A for loop repeats a whole task for each value; create an empty container before the loop to keep results.
  • map() returns a list, map_dbl() a number vector, and walk() just does something (like saving files) for each element. In base R code you will see lapply() (always a list) and sapply() (it guesses the shape).

Where to go next: R for Data Science (free online) — chapters on functions and iteration; The Epidemiologist R Handbook — applied examples for public health.