The Analogy: The Commercial Laundry's Sorting Trolleys
A laundry serving four hotels takes in one mixed stream of dirty linen off a single conveyor. Before anything can be washed, a sorter reads the woven tag on each sheet and drops it into one of four trolleys, each painted with a hotel's name. From that moment the whole plant works trolley by trolley: a trolley is wheeled to a washer as a unit, weighed as a unit, and its wash is booked to one hotel. The paint on the trolley is the only thing that turns a heap of identical white sheets into four separate jobs.
The label decides what every later number means. When the checker parks a trolley on the floor scale and writes down 3000 grams, that figure is the Grand Hotel's load, not the plant's throughput, because the trolley only ever holds Grand Hotel linen. The same scale, the same reading, the same pencil -- but the number is a per-hotel number purely because of the word painted on the side. Nothing about the weighing says so; the meaning rides entirely on the label the sorter applied upstream.
The label also decides how far a summary reaches. If the sorter had used finer trolleys, one per hotel and per linen type, then a weight would be a per-hotel-per-type figure, and to get back to a per-hotel total someone has to tip the sheet trolley and the towel trolley for one hotel into a single bin and weigh that. Coarsening the grouping is a deliberate act of tipping trolleys together; it does not happen just because you stopped looking at the fine ones.
The failure that costs the plant real money is the trolley that never gets its label scrubbed off. A washer finishes the Grand Hotel load, the trolley is not returned to the general pool, and the next person wheels it under the intake chute and starts filling it with everyone's linen -- but the scale ticket still prints "GRAND". Now a whole-plant weight is booked to one hotel, and because the ticket looks exactly like every honest per-hotel ticket, nobody notices until a hotel disputes an impossible bill. In dplyr the painted-on label is the grouping a frame carries, and the trolley nobody emptied is a frame you forgot to ungroup: every count and every sum downstream is silently still per-group when you have long since started thinking about the whole.
Syntax or Core Structure
group_by() paints the labels; summarize() weighs each trolley and hands back one row per group. On a plain data frame the pair reads almost like a sentence: split by hotel, then per hotel report the item count and the total grams.
library(dplyr)
linen <- data.frame(
item = c("S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8"),
hotel = c("GRAND", "GRAND", "GRAND", "PARK", "PARK", "PARK", "PARK", "BAY"),
kind = c("sheet", "sheet", "towel", "sheet", "towel", "towel", "sheet", "towel"),
w = c(1200L, 1180L, 620L, 1210L, 640L, 610L, 1190L, 630L),
stringsAsFactors = FALSE
)
by_hotel <- linen |>
group_by(hotel) |>
summarize(items = n(), grams = sum(w), .groups = "drop")
writeLines(sprintf("%-8s: %d", "rows in", nrow(linen)))
writeLines(sprintf("%-8s: %d", "groups", nrow(by_hotel)))
writeLines(sprintf("%-8s %5s %7s", "HOTEL", "ITEMS", "GRAMS"))
writeLines(sprintf("%-8s %5d %7d", by_hotel$hotel, by_hotel$items, by_hotel$grams))
writeLines(sprintf("%-8s: %s", "grouped?", inherits(by_hotel, "grouped_df")))
writeLines(sprintf("%-8s: %d", "total", sum(by_hotel$grams)))
Output:
rows in : 8
groups : 3
HOTEL ITEMS GRAMS
BAY 1 630
GRAND 3 3000
PARK 4 3650
grouped?: FALSE
total : 7280
Eight rows go in and three come out, one per distinct hotel, because summarize() collapses each group to a single row. The groups arrive in alphabetical order -- BAY, GRAND, PARK -- since group_by() sorts by the grouping key rather than preserving the order the rows came in. n() counts the rows in each group and sum(w) adds their weights, and the three group totals add back to 7280, the weight of the whole intake.
The .groups = "drop" argument is the trolley being scrubbed clean: it says the result should carry no grouping, which is why inherits(by_hotel, "grouped_df") prints FALSE. Left off, summarize() would peel away only the last grouping key and print a message about the grouping it kept, and the very next verb would still be working trolley by trolley. Naming the argument makes the reach of the summary explicit instead of leaving it to a default you have to remember. Note too that nothing here ever prints by_hotel itself; every figure is pulled out as a plain vector and formatted by hand, because a grouped frame prints a header that is not the report you want.
Technical Depth: What Grouping Changes and What It Does Not
Grouping is a label the frame carries, not an operation. It changes how the next verb behaves and nothing about the rows themselves. The table below is the whole of it: the same verb does different things depending on whether a label is present.
| Verb after group_by | What it does per group | Rows returned |
|---|---|---|
summarize() | one summary row per group | one per group |
mutate() | computes within the group, keeps rows | every row |
filter() | tests each row against its group | those that pass |
slice_max() | top rows within each group | up to n per group |
n() | counts rows in the current group | used inside a verb |
arrange() | ignores grouping entirely | every row |
Two rows there are the usual traps. arrange() does not sort within groups, so ordering after grouping rarely does what people expect, and mutate() keeps every row while summarize() keeps one -- choosing the wrong one is the single most common grouping mistake.
summarize collapses, mutate broadcasts
graded <- linen |>
group_by(hotel) |>
mutate(hotel_grams = sum(w),
rank_in_hotel = rank(-w, ties.method = "first")) |>
ungroup()
collapsed <- linen |>
group_by(hotel) |>
summarize(hotel_grams = sum(w), .groups = "drop")
writeLines(sprintf("%-16s: %d", "mutate rows", nrow(graded)))
writeLines(sprintf("%-16s: %d", "summarize rows", nrow(collapsed)))
writeLines(sprintf("%-16s: %s", "still grouped", inherits(graded, "grouped_df")))
writeLines(sprintf("%-16s: %s", "hotel grams", paste(graded$hotel_grams, collapse = " ")))
writeLines(sprintf("%-16s: %s", "rank in hotel", paste(graded$rank_in_hotel, collapse = " ")))
writeLines(sprintf("%-16s: %d", "grand total row", graded$hotel_grams[1]))
Output:
mutate rows : 8
summarize rows : 3
still grouped : FALSE
hotel grams : 3000 3000 3000 3650 3650 3650 3650 630
rank in hotel : 1 2 3 1 3 4 2 1
grand total row : 3000
A grouped mutate() computes one number per group and then broadcasts it back across every row of that group: all three Grand rows carry 3000, all four Park rows carry 3650. That is exactly what you want when a per-row calculation needs its group's total -- a share, a rank, a deviation from the group mean -- and it is the tool summarize() cannot be, because summarize() throws the rows away. The rank column is computed within each hotel too, so both Grand and Park have a rank 1, their own heaviest item. The ungroup() at the end matters: without it graded would still be grouped and every later verb would keep splitting by hotel.
Multiple keys, and how a summary peels one off
by_pair <- linen |>
group_by(hotel, kind) |>
summarize(items = n(), grams = sum(w), .groups = "drop")
counts <- linen |> count(hotel)
rollup <- by_pair |>
group_by(hotel) |>
summarize(grams = sum(grams), .groups = "drop")
writeLines(sprintf("%-16s: %d", "two-key rows", nrow(by_pair)))
writeLines(sprintf("%-16s: %s", "keys",
paste(sprintf("%s %s", by_pair$hotel, by_pair$kind), collapse = ", ")))
writeLines(sprintf("%-16s: %s", "grams by pair", paste(by_pair$grams, collapse = " ")))
writeLines(sprintf("%-16s: %s", "count n", paste(counts$n, collapse = " ")))
writeLines(sprintf("%-16s: %s", "rollup hotels", paste(rollup$hotel, collapse = " ")))
writeLines(sprintf("%-16s: %s", "rollup grams", paste(rollup$grams, collapse = " ")))
writeLines(sprintf("%-16s: %s", "rollup matches",
isTRUE(all.equal(rollup$grams, c(630, 3000, 3650)))))
Output:
two-key rows : 5
keys : BAY towel, GRAND sheet, GRAND towel, PARK sheet, PARK towel
grams by pair : 630 2380 620 2400 1250
count n : 1 3 4
rollup hotels : BAY GRAND PARK
rollup grams : 630 3000 3650
rollup matches : TRUE
Grouping by two keys produces one row per observed combination, and there are five, not six, because BAY only ever sent towels. count(hotel) is the shorthand for grouping and calling n(), and here it gives the same 1, 3, 4 as before. The roll-up is the deliberate coarsening from the analogy: to turn per-hotel-per-kind figures back into per-hotel figures you group the summary again by hotel alone and sum, and the result matches the one-key totals from the first example exactly. Reducing the grouping is an operation you perform, not a thing that happens by wishing the finer split away.
The ungroup trap, and slicing per group
oops <- linen |> group_by(hotel) |> mutate(seen = n())
fixed <- linen |> group_by(hotel) |> ungroup() |> mutate(seen = n())
top <- linen |>
group_by(hotel) |>
slice_max(w, n = 1, with_ties = FALSE) |>
ungroup()
heavy <- linen |>
group_by(hotel) |>
filter(w == max(w)) |>
ungroup()
writeLines(sprintf("%-16s: %s", "grouped n()", paste(oops$seen, collapse = " ")))
writeLines(sprintf("%-16s: %s", "ungrouped n()", paste(fixed$seen, collapse = " ")))
writeLines(sprintf("%-16s: %d", "top rows", nrow(top)))
writeLines(sprintf("%-16s: %s", "top items", paste(top$item, collapse = " ")))
writeLines(sprintf("%-16s: %s", "top weights", paste(top$w, collapse = " ")))
writeLines(sprintf("%-16s: %d", "filtered rows", nrow(heavy)))
writeLines(sprintf("%-16s: %s", "filtered items", paste(sort(heavy$item), collapse = " ")))
Output:
grouped n() : 3 3 3 4 4 4 4 1
ungrouped n() : 8 8 8 8 8 8 8 8
top rows : 3
top items : S8 S1 S4
top weights : 630 1200 1210
filtered rows : 3
filtered items : S1 S4 S8
The first two lines are the whole hazard in miniature. n() on a still-grouped frame reports the size of each row's group -- 3 for the Grand rows, 4 for Park, 1 for Bay -- while the same call after ungroup() reports 8, the size of the frame. Neither is wrong; they answer different questions, and the only thing that distinguishes them is whether the trolley still wears its label. Code that meant the whole-frame count but ran on a grouped frame gets a plausible, wrong number and no error. slice_max(w, n = 1) takes the heaviest row of each group and returns three rows in group order, while the grouped filter(w == max(w)) keeps every row equal to its group maximum, which here is also three but would be more under a tie. Both end with ungroup(), because a slice or filter leaves the grouping in place.
Real World Example: A Week's Laundry Billing
A week of intake is twenty-four batches across three hotels, each batch a weight in kilograms and a linen kind that sets the per-kilogram rate. The plant wants a bill per hotel sorted by charge, the heaviest single batch each hotel sent, and a reconciliation that the per-hotel charges add back to the week's total.
library(dplyr)
RATE <- c(sheet = 5L, towel = 3L, robe = 8L)
batch <- data.frame(
id = sprintf("L%02d", 1:24),
hotel = c(rep("GRAND", 9), rep("PARK", 9), rep("BAY", 6)),
kind = c("sheet", "sheet", "towel", "robe", "sheet", "towel", "robe", "towel", "sheet",
"sheet", "towel", "robe", "sheet", "towel", "sheet", "robe", "towel", "sheet",
"towel", "robe", "sheet", "sheet", "towel", "robe"),
kg = c(20L, 22L, 8L, 5L, 18L, 10L, 6L, 10L, 22L,
19L, 12L, 4L, 17L, 9L, 23L, 3L, 11L, 11L,
7L, 5L, 12L, 16L, 8L, 7L),
stringsAsFactors = FALSE
)
priced <- batch |> mutate(charge = kg * RATE[kind])
per_hotel <- priced |>
group_by(hotel) |>
summarize(batches = n(), kg = sum(kg), charge = sum(charge), .groups = "drop") |>
arrange(desc(charge), hotel)
week_batches <- nrow(priced)
week_kg <- sum(priced$kg)
week_charge <- sum(priced$charge)
heavy <- priced |>
group_by(hotel) |>
slice_max(kg, n = 1, with_ties = FALSE) |>
ungroup() |>
arrange(hotel)
grand_max <- max(priced$kg[priced$hotel == "GRAND"])
grand_tie <- priced |> filter(hotel == "GRAND", kg == grand_max) |> pull(id)
share <- sprintf("%.1f", 100 * per_hotel$charge / week_charge)
rule <- strrep("-", 30)
writeLines(sprintf("%-8s%8s%6s%8s", "HOTEL", "BATCHES", "KG", "CHARGE"))
writeLines(rule)
writeLines(sprintf("%-8s%8d%6d%8d", per_hotel$hotel, per_hotel$batches,
per_hotel$kg, per_hotel$charge))
writeLines(rule)
writeLines(sprintf("%-8s%8d%6d%8d", "TOTAL", week_batches, week_kg, week_charge))
writeLines("")
writeLines(sprintf("%-8s%-7s%-7s%5s", "HOTEL", "BATCH", "KIND", "KG"))
writeLines(sprintf("%-8s%-7s%-7s%5d", heavy$hotel, heavy$id, heavy$kind, heavy$kg))
writeLines("")
writeLines(sprintf("%-18s: %d", "batches", week_batches))
writeLines(sprintf("%-18s: %d", "kg total", week_kg))
writeLines(sprintf("%-18s: %d", "charge total", week_charge))
writeLines(sprintf("%-18s: %d", "hotels", nrow(per_hotel)))
writeLines(sprintf("%-18s: %d", "sum hotel kg", sum(per_hotel$kg)))
writeLines(sprintf("%-18s: %d", "sum hotel charge", sum(per_hotel$charge)))
writeLines(sprintf("%-18s: %s", "kg reconciles", sum(per_hotel$kg) == week_kg))
writeLines(sprintf("%-18s: %s", "charge reconciles", sum(per_hotel$charge) == week_charge))
writeLines(sprintf("%-18s: %s", "top per hotel", paste(heavy$id, collapse = " ")))
writeLines(sprintf("%-18s: %s", "grand tie kg", paste(grand_tie, collapse = " ")))
writeLines(sprintf("%-18s: %s", "week share pct",
paste(sprintf("%s %s", per_hotel$hotel, share), collapse = " ")))
writeLines(sprintf("%-18s: %.1f", "shares sum to", sum(as.numeric(share))))
Output:
HOTEL BATCHES KG CHARGE
------------------------------
GRAND 9 121 582
PARK 9 109 502
BAY 6 55 281
------------------------------
TOTAL 24 285 1365
HOTEL BATCH KIND KG
BAY L22 sheet 16
GRAND L02 sheet 22
PARK L15 sheet 23
batches : 24
kg total : 285
charge total : 1365
hotels : 3
sum hotel kg : 285
sum hotel charge : 1365
kg reconciles : TRUE
charge reconciles : TRUE
top per hotel : L22 L02 L15
grand tie kg : L02 L09
week share pct : GRAND 42.6 PARK 36.8 BAY 20.6
shares sum to : 100.0
The bill is a single grouped summarize() with three aggregates, arranged after the grouping is dropped because arrange() ignores a live grouping. Each hotel's charge is the sum of kg * RATE[kind] over its batches, and the rate lookup is a named vector indexed by the kind column, so a sheet batch is billed at 5 and a robe at 8 without a join. The per-kilogram rates turn 285 kilograms into 1365 units of charge, and the three hotels split that as 582, 502, 281.
The reconciliation lines are the point of the exercise. sum(per_hotel$kg) adds the three group totals and compares them to week_kg, which was computed on the ungrouped frame; both are 285 and kg reconciles is TRUE. This is the check that would have caught the unemptied trolley from the analogy: if the per-hotel sums had been produced on a frame that was still grouped by something finer, or the week total computed on a grouped frame, the two numbers would part company and the TRUE would flip. The week shares are rounded to one decimal and add to exactly 100.0 here, which is luck, not a guarantee.
The heaviest-batch table is where the design starts to leak. It comes from slice_max(kg, n = 1, with_ties = FALSE), and grand tie kg shows why that flag is dangerous: Grand sent two batches at 22 kilograms, L02 and L09, and the report names only L02. It is cased -- printed -- purely because it sits earlier in the frame; relabel the batches and the "heaviest batch" for Grand changes, though the plant sent two equally heavy loads. A report that silently drops a tie is telling the reader there was one winner when there were two.
Three more flaws sit in the same code. The rate lookup RATE[kind] returns NA for any kind not in the vector, and since no sum() here uses na.rm, a single mistyped kind -- "sheets" for "sheet" -- would turn that batch's charge, then its hotel's charge, then the week total, then the reconciliation into NA, and charge reconciles would print NA rather than FALSE, which is not the loud failure a billing run deserves. The week total is computed independently from the batches rather than derived from per_hotel, so the reconciliation only proves the two calculations agree with each other, not that either matches what the hotels actually owe. And the shares are rounded before they are summed, so on a different week the printed percentages could add to 99.9 or 100.1 while the line still claims to reconcile; nothing forces the rounded parts to equal the rounded whole.
Common Mistakes
- Forgetting to
ungroup(). A frame stays grouped aftermutate(),filter(),slice()and evensummarize()with multiple keys. Every later verb keeps splitting by the old key, andn(),sum()andmean()quietly report per-group figures when you meant the whole.
- Reaching for
summarize()when you needmutate().summarize()throws the rows away and returns one per group; if you want a group total attached to every original row -- a share, a rank, a group mean -- it is a groupedmutate()you want, which keeps the rows.
- Expecting
summarize()to drop all grouping. With one key it drops to ungrouped, but with several it peels off only the last and leaves the rest, printing a message you probably ignored. Pass.groups = "drop"so the reach of the summary is explicit.
- Omitting
na.rmin a group aggregate. A singleNAin a group turns that group'ssum()ormean()intoNA, and the bad group sits in the output looking like every other row. Decide what a missing value means before you aggregate over it.
- Trusting
arrange()to sort within groups.arrange()ignores grouping and sorts the whole frame. If you grouped and then arranged expecting per-group order, you got global order instead; sort after you have summarized, or arrange by the group key as well.
- Assuming
slice_max(n = 1)returns one row per group. Ties are kept by default, so a group with two rows at the maximum returns both, and a downstream count is off.with_ties = FALSEforces one, but then silently drops the tie -- neither is free.
- Grouping on a column you have not made yet.
group_by()runs before themutate()further down the chain, so grouping by a derived column has to come after themutate()that creates it, not before.
- Printing a grouped frame or a tibble as your report. A
grouped_dfprints a group header and a truncated preview, not the figures you want, and on some builds that header contains non-ASCII characters. Pull the columns out as vectors and format them yourself.
- Believing
group_by()keeps the original row order. It sorts by the grouping key, so the summary comes out alphabetical or numeric by key, not in the order the data arrived. If order matters, record it before grouping orarrange()afterwards.
Best Practices
- End every grouped pipeline with
ungroup(), or drop the grouping in thesummarize()that produced the result, so nothing downstream inherits a label it should not have.
- Choose between
summarize()andmutate()by asking whether you need one row per group or every row back. Say which in a comment when the chain is long enough that the answer is not obvious.
- Prefer
count(x)togroup_by(x) |> summarize(n = n())for a plain tally; it is shorter and it ungroups for you.
- Decide the treatment of missing values explicitly. Pass
na.rm = TRUEwhen a missing value should be skipped, and leave it off deliberately when a missing value should poison the group so you see it.
- Arrange after you summarize, never before, since grouping discards any order you set up earlier.
- Name summary columns for what they hold, not the function that made them:
total_kg, notsum. The next reader reads the name far more often than the code.
- Reduce a multi-key summary to a coarser one by grouping the summary again and summing, rather than trying to get there in one step; the roll-up is explicit and easy to check.
- Reconcile group totals against an independently computed whole-frame total, and print the
TRUE. It is the cheapest guard against a grouping you forgot to drop.
Practice Exercises
- Extend the billing run with a per-kind breakdown: group by
hotelandkind, sum the charge, and then roll the result back up to per-hotel charges. Assert that the rolled-up figures equal theper_hotelcharges from the two-key summary.
- Fix the dropped tie. Replace the heaviest-batch table so a hotel that sent two equally heavy batches lists both, and print how many hotels had a tie at their maximum. Confirm Grand now shows L02 and L09.
- Guard the rate lookup. Before pricing, check that every
kindin the data is a name ofRATE; if any is not, print the offending kinds and stop rather than letting anNAcharge flow into the total.
- Make the shares honest. Round the per-hotel percentages so they sum to exactly 100.0, giving the rounding remainder to the largest hotel, and print which hotel absorbed the adjustment and by how much.