Exercise · Beginner
The grouping that lingers
Four dplyr pipelines, each returning a plausible number that answers a different question from the one asked. Find the leftover grouping, say what each actually computed, and rewrite it.
None of these pipelines errors. Each returns a table with the right column names and numbers of a plausible size. Three of them answer a different question from the one in the comment above.
The file
muac-screening-artibonite-2024.v1.csv — 4,218 screening records from twelve
communes in Artibonite, Haiti. Synthetic, and shaped like the real thing.
The pipelines
# 1. What share of the district's screenings did each commune-month contribute?
muac |>
group_by(commune, month) |>
summarise(n = n()) |>
mutate(share = n / sum(n))
# 2. The five commune-months with the most screenings, district-wide.
muac |>
group_by(commune, month) |>
summarise(n = n()) |>
slice_max(n, n = 5)
# 3. The district's mean MUAC.
muac |>
group_by(commune) |>
summarise(mean_muac = mean(muac_mm))
# 4. How many children were screened in each commune, including those whose
# commune was not recorded?
muac |>
filter(!is.na(commune)) |>
count(commune)
The task
For each pipeline:
- Say what it actually computes, in one sentence. Be specific — “the share within something” is not an answer; name the something.
- Show the evidence.
dplyr::group_vars()andclass()on the intermediate result will settle three of the four without you having to reason it out. - Rewrite it so it answers the question in the comment.
The questions to answer in prose
Three sentences each.
1. Two of these bugs come from the same cause. Name it, and explain why the
summarise() message is easy to miss in a script that produces twenty tables.
2. Pipeline 3 returns NA for at least one commune. Explain why R does that
rather than skipping the missing values, and say what na.rm = TRUE would do to
the denominator — not just to the numerator.
3. Pipeline 4’s filter looks like it answers the question and does the opposite. What would a reader of the resulting table conclude about the number of children screened, and what is the smallest change that fixes it?
What to hand in
A single R script that runs top to bottom and prints, for each pipeline, the original result, the diagnosis, and the corrected result.
How to know you are done
Every corrected pipeline uses either .groups = "drop" or .by =, and none of
them relies on a grouping that survives the call. If your script contains a path
starting with /Users or C:, or a setwd(), it is not done — see lesson 1.