Unit 06.01: Always carry n
Every grouped summary needs a count beside it, because a mean of one is still a mean.
Always carry n
group_by() and summarise() collapse many rows to one per group, and in doing so they discard how many rows each group had. A ward with one month of data and a ward with twelve produce identical-looking rows, and the first will frequently top the ranking by accident.
Including n() costs one line and prevents the entire class of conclusions drawn from a group of two.
There is a second trap in the arithmetic. The mean of the group means is not the overall mean unless every group is the same size — averaging averages weights each group equally regardless of how much data it contains.
This block groups three wards of very different sizes.
suppressPackageStartupMessages(library(dplyr))
ward_visits <- data.frame(
ward = c("North", "North", "North", "South", "South", "East"),
month = c("Jan", "Feb", "Mar", "Jan", "Feb", "Jan"),
visits = c(412, 455, 431, 388, 401, 502)
)
by_ward <- ward_visits |>
group_by(ward) |>
summarise(months = n(),
total = sum(visits),
mean = round(mean(visits), 1),
.groups = "drop")
print(by_ward)
cat("\nEast's mean is the highest at", max(by_ward$mean),
"-- from", by_ward$months[by_ward$ward == "East"], "month.\n")
cat("The `months` column is the reason nobody quotes that ranking unguarded.\n\n")
# The mean of the group means is not the overall mean unless groups are equal.
cat("Mean of the three ward means:", round(mean(by_ward$mean), 1), "\n")
cat("Mean across all six rows :", round(mean(ward_visits$visits), 1), "\n")
East has the highest mean at 502, from 1 month. North's 433 comes from three months and South's 394 from two. Without the months column the ranking reads as a finding about demand; with it, East's position is visibly an artefact of a single observation. The last two lines make the weighting point: the mean of the three ward means is 443.1, while the mean across all six rows is 431.5.
The mistake this prevents
The mistake is averaging pre-computed averages. Each group's mean carries equal weight regardless of its size, so the smallest group influences the result as much as the largest.
Takeaway
Include n() in every summarise(), and show it in any table you publish. To get an overall mean, compute it from the raw rows rather than from the group means.
