The Analogy: The Bottling Hall's Conveyor Line
A bottling hall is one long conveyor with single-purpose stations bolted along it in a fixed order: rinser, filler, capper, labeller, case packer. No station knows what any other station does. Each one takes whatever arrives on the belt, does its single job to it, and puts it back on the belt travelling the same direction. Nobody carries a bottle backwards to the rinser because a label came out crooked. The bottle goes into the reject bin and a fresh one starts at the top of the line.
The order of the stations is the recipe, and it is not interchangeable. Swap the filler and the capper and you cap empty bottles. Swap the labeller and the filler and the labels come off wet. Reading the line from one end to the other tells you exactly what happens to a bottle and in what order, which is why a plant manager can walk a visitor down the hall and explain the whole product without opening a manual.
Somewhere early in the line there is a check-weigher with a diverter gate, and bottles below the fill weight get pushed off the belt. Where that gate sits is an economic decision as much as a correctness one. Put it before the labeller and an underfilled bottle costs you one bottle. Put it after and the same bottle costs you a bottle plus a label plus the labeller's time. Every plant that has thought about it puts its cheapest and most brutal test first.
The line hurts you at the tally board. The case packer at the far end counts cases and chalks the number up, and the shift is judged on that number. When a station quietly loses bottles -- a jam that clears itself by shoving two bottles down the waste chute, a gate that sticks half open -- the tally board still reads plausibly. It reads a little low, and nobody can say which station ate the difference, because the only count anyone wrote down was the one at the end. A line that counts bottles only where they leave cannot tell a good shift from a leaking one.
Syntax or Core Structure
dplyr gives you a small set of verbs that each take a data frame as their first argument and return a data frame. That one shape is what makes them chainable. The pipe is not a dplyr feature and does nothing clever: x |> f(y) is rewritten to f(x, y) before anything runs, so a chain of pipes is a chain of nested calls written in the order they happen rather than inside out.
library(dplyr)
runs <- data.frame(
id = c("R1", "R2", "R3", "R4", "R5"),
line = c("L1", "L2", "L1", "L2", "L1"),
bottles = c(480L, 512L, 495L, 468L, 503L),
rejects = c(6L, 11L, 4L, 9L, 5L),
stringsAsFactors = FALSE
)
nested <- arrange(
mutate(filter(runs, line == "L1"), good = bottles - rejects),
desc(good)
)
piped <- runs |>
filter(line == "L1") |>
mutate(good = bottles - rejects) |>
arrange(desc(good))
tag_last <- "L1" %>% paste0("2026-", .)
native <- tag_last |> gsub(pattern = "L1", replacement = "LINE 1", x = _)
writeLines(sprintf("%-14s: %d", "rows in", nrow(runs)))
writeLines(sprintf("%-14s: %d", "rows kept", nrow(piped)))
writeLines(sprintf("%-14s: %s", "same as nested", identical(piped, nested)))
writeLines(sprintf("%-14s: %s", "ids in order", paste(piped$id, collapse = " ")))
writeLines(sprintf("%-14s: %s", "good counts", paste(piped$good, collapse = " ")))
writeLines(sprintf("%-14s: %s", "placeholder", tag_last))
writeLines(sprintf("%-14s: %s", "native _", native))
Output:
rows in : 5
rows kept : 3
same as nested: TRUE
ids in order : R5 R3 R1
good counts : 498 491 474
placeholder : 2026-L1
native _ : 2026-LINE 1
The first thing to take from this is that identical(piped, nested) is TRUE. The pipe bought readability and nothing else, which is why you can always debug a chain by unwrapping it. The two placeholder lines are the exception to the rewrite: normally the value goes in as the first argument, and a placeholder is how you put it somewhere else. In magrittr's %>% the placeholder is . and it may appear anywhere; in the native |> it is _ and it must be handed to a named argument, which is why the gsub call names x.
Technical Depth: What Each Verb Promises About the Rows
Every verb changes exactly one thing about the frame and leaves the rest alone: arrange() cannot change a total, select() cannot change a row count, and filter() cannot change a value. When a number comes out wrong, that mapping tells you which line to look at.
The one-table verbs
| Verb | What it changes | What it always returns |
|---|---|---|
filter() | which rows survive | a frame with the same columns |
select() | which columns, and their order | a frame, never a bare vector |
rename() | one or more column names | every row and column, renamed |
relocate() | column order only | the same data, reordered |
mutate() | adds or replaces columns | the same rows in the same order |
arrange() | row order only | the same rows, missing values last |
distinct() | drops repeated rows | the first occurrence of each |
pull() | extracts one column | a vector, not a frame |
Two rows are worth reading twice. arrange() puts missing values last whichever direction you sort, so desc() does not bring them to the top. And pull() is the only verb here that leaves the world of frames, which makes it the right way out of a chain and the wrong thing in the middle of one.
filter keeps what is TRUE, and nothing else
qc <- data.frame(
id = c("B1", "B2", "B3", "B4", "B5", "B6"),
fill = c(498, 507, NA, 501, 492, 500),
cap = c(TRUE, TRUE, TRUE, NA, FALSE, TRUE),
sku = c("COLA", "COLA", "TONIC", "LEMON", "TONIC", "COLA"),
stringsAsFactors = FALSE
)
in_band <- qc |> filter(fill >= 495, fill <= 505)
amp <- qc |> filter(fill >= 495 & fill <= 505)
capped <- qc |> filter(cap)
band_cap <- qc |> filter(fill >= 495, fill <= 505, cap)
in_set <- qc |> filter(sku %in% c("COLA", "TONIC"))
pass <- qc |> filter(!is.na(fill), !is.na(cap), between(fill, 495, 505), cap)
fail <- qc |> filter(!is.na(fill), !is.na(cap), !(between(fill, 495, 505) & cap))
unknown <- qc |> filter(is.na(fill) | is.na(cap))
writeLines(sprintf("%-17s: %d", "rows total", nrow(qc)))
writeLines(sprintf("%-17s: %d", "in band", nrow(in_band)))
writeLines(sprintf("%-17s: %s", "comma same as &", identical(in_band, amp)))
writeLines(sprintf("%-17s: %d", "capped", nrow(capped)))
writeLines(sprintf("%-17s: %d", "band and cap", nrow(band_cap)))
writeLines(sprintf("%-17s: %s", "sku in set", paste(in_set$id, collapse = " ")))
writeLines(sprintf("%-17s: %d", "pass", nrow(pass)))
writeLines(sprintf("%-17s: %d", "fail", nrow(fail)))
writeLines(sprintf("%-17s: %d", "unknown", nrow(unknown)))
writeLines(sprintf("%-17s: %s", "splits reconcile",
nrow(pass) + nrow(fail) + nrow(unknown) == nrow(qc)))
Output:
rows total : 6
in band : 3
comma same as & : TRUE
capped : 4
band and cap : 2
sku in set : B1 B2 B3 B5 B6
pass : 2
fail : 2
unknown : 2
splits reconcile : TRUE
Six rows go in and the band test keeps three, because B3 has no weight and NA >= 495 is NA, which is not TRUE. Several commas inside one filter() mean the same thing as & between the conditions, which identical() confirms. The bottom half is the interesting part: band_cap keeps two rows and so does pass, but they are not the same statement. band_cap silently merges "failed the test" with "was never tested", while the three-way split records the two untested bottles as unknown and reconciles back to six. A chain that only ever asks for the survivors cannot tell you which station lost the rest.
select, rename and relocate work on the names
cols <- qc |> select(id, fill)
without <- qc |> select(-cap)
nums <- qc |> select(where(is.numeric))
reordered <- qc |> select(sku, id)
moved <- qc |> relocate(sku, .before = fill)
renamed <- qc |> rename(fill_ml = fill)
vec <- qc |> pull(fill)
one_col <- qc |> select(fill)
want <- "fill"
dyn <- qc |> select(all_of(want))
writeLines(sprintf("%-17s: %s", "select names", paste(names(cols), collapse = " ")))
writeLines(sprintf("%-17s: %s", "negative select", paste(names(without), collapse = " ")))
writeLines(sprintf("%-17s: %s", "numeric only", paste(names(nums), collapse = " ")))
writeLines(sprintf("%-17s: %s", "select reorders", paste(names(reordered), collapse = " ")))
writeLines(sprintf("%-17s: %s", "relocated", paste(names(moved), collapse = " ")))
writeLines(sprintf("%-17s: %s", "renamed", paste(names(renamed), collapse = " ")))
writeLines(sprintf("%-17s: %s", "pull class", class(vec)))
writeLines(sprintf("%-17s: %s", "select class", class(one_col)))
writeLines(sprintf("%-17s: %s", "all_of names", paste(names(dyn), collapse = " ")))
Output:
select names : id fill
negative select : id fill sku
numeric only : fill
select reorders : sku id
relocated : id sku fill cap
renamed : id fill_ml cap sku
pull class : numeric
select class : data.frame
all_of names : fill
select() is also the cheapest way to reorder columns, since the frame comes back in the order you listed, and where(is.numeric) skips cap because a logical column is not numeric. The last three lines are the distinction that costs the most time: pull() hands back a vector and select() a one-column frame, and the two are not interchangeable in the line that follows. all_of() is how a column name held in a variable gets used, because bare want would look for a column called want.
mutate builds columns, case_when labels them, arrange moves them
step <- qc |>
mutate(dev = fill - 500,
off = abs(dev),
band = if_else(off <= 5, "IN", "OUT", missing = "UNWEIGHED"))
loose <- ifelse(step$off <= 5, "IN", "OUT")
mixed <- try(if_else(step$off <= 5, "IN", 0), silent = TRUE)
tagged <- qc |> mutate(reason = case_when(
is.na(fill) ~ "no weight",
fill < 495 ~ "underfill",
fill > 505 ~ "overfill",
is.na(cap) ~ "cap unknown",
!cap ~ "cap bad",
.default = "ok"))
recut <- qc |> mutate(reason = case_when(
is.na(fill) ~ "no weight",
is.na(cap) ~ "cap unknown",
!cap ~ "cap bad",
fill < 495 ~ "underfill",
fill > 505 ~ "overfill",
.default = "ok"))
ties <- data.frame(id = c("T1", "T2", "T3", "T4"), n = c(9L, 7L, 9L, 5L))
dup <- data.frame(sku = c("COLA", "COLA", "TONIC"), lot = c("A", "B", "C"))
na_last <- is.na(tail(arrange(qc, fill)$fill, 1)) &&
is.na(tail(arrange(qc, desc(fill))$fill, 1))
writeLines(sprintf("%-17s: %s", "dev values", paste(step$dev, collapse = " ")))
writeLines(sprintf("%-17s: %s", "band values", paste(step$band, collapse = " ")))
writeLines(sprintf("%-17s: %d", "ifelse NA count", sum(is.na(loose))))
writeLines(sprintf("%-17s: %d", "if_else NA count", sum(is.na(step$band))))
writeLines(sprintf("%-17s: %s", "if_else mixed",
if (inherits(mixed, "try-error")) "errored" else "passed"))
writeLines(sprintf("%-17s: %s", "first match", tagged$reason[5]))
writeLines(sprintf("%-17s: %s", "clauses reordered", recut$reason[5]))
writeLines(sprintf("%-17s: %s", "arrange asc", paste(arrange(qc, fill)$id, collapse = " ")))
writeLines(sprintf("%-17s: %s", "arrange desc", paste(arrange(qc, desc(fill))$id, collapse = " ")))
writeLines(sprintf("%-17s: %s", "NA last both ways", na_last))
writeLines(sprintf("%-17s: %d", "slice_max ties", nrow(slice_max(ties, n, n = 1))))
writeLines(sprintf("%-17s: %d", "slice_max strict",
nrow(slice_max(ties, n, n = 1, with_ties = FALSE))))
writeLines(sprintf("%-17s: %d", "distinct rows", nrow(distinct(dup, sku))))
writeLines(sprintf("%-17s: %s", "distinct keep all",
paste(distinct(dup, sku, .keep_all = TRUE)$lot, collapse = " ")))
Output:
dev values : -2 7 NA 1 -8 0
band values : IN OUT UNWEIGHED IN OUT IN
ifelse NA count : 1
if_else NA count : 0
if_else mixed : errored
first match : underfill
clauses reordered: cap bad
arrange asc : B5 B1 B6 B4 B2 B3
arrange desc : B2 B4 B6 B1 B5 B3
NA last both ways: TRUE
slice_max ties : 2
slice_max strict : 1
distinct rows : 2
distinct keep all: A C
One mutate() call can use a column it created two lines earlier, which is why off may lean on dev. The two conditional functions then part company: ifelse() passes the missing weight through as NA, while if_else() has a missing = argument that lets you name what an unknown is, and refuses to mix a string with a number at all.
The two case_when() calls carry the same five tests and disagree about B5, which is both underfilled and badly capped. First match wins, so clause order is policy, not formatting. arrange() then shows its own rule: B3 sits last ascending and last descending, because missing values are parked at the end either way. slice_max() returns both nines by default and one under with_ties = FALSE, and distinct() keeps the first row of each repeated group, which is why lot A survives and lot B does not.
Real World Example: A Shift Audit for the Bottling Line
A shift of 24 bottles comes off two lines. The plant wants three things from one script: a funnel saying how many bottles each check removed, a tally of why bottles were rejected, and a packing list for the twelve that go into a case.
library(dplyr)
SPEC_LO <- 495L
SPEC_HI <- 505L
CASE_N <- 12L
NOMINAL <- 500L
bottles <- data.frame(
id = sprintf("B%02d", 1:24),
line = c(rep("L1", 8), rep("L2", 8), rep("L1", 4), rep("L2", 4)),
sku = c("COLA", "COLA", "COLA", "COLA", "LEMON", "LEMON", "LEMON", "LEMON",
"TONIC", "TONIC", "TONIC", "TONIC", "COLA", "COLA", "COLA", "COLA",
"COLA", "LEMON", "TONIC", "TONIC", "LEMON", "COLA", "COLA", "COLA"),
fill = c(503, 509, 499, 505, NA, 498, 491, 501, 498, 500, 500, 502,
NA, 498, 504, 511, 496, 487, 500, 499, NA, 495, 502, 501),
cap = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
FALSE, TRUE, NA, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE),
stringsAsFactors = FALSE
)
tagged <- bottles |> mutate(reason = case_when(
is.na(fill) ~ "no weight",
fill < SPEC_LO ~ "underfill",
fill > SPEC_HI ~ "overfill",
is.na(cap) ~ "cap unknown",
!cap ~ "cap bad",
.default = "ok"))
step2 <- bottles |> filter(!is.na(fill))
step3 <- step2 |> filter(between(fill, SPEC_LO, SPEC_HI))
step4 <- step3 |> filter(!is.na(cap))
passed <- step4 |> filter(cap)
stations <- c("records in", "weight recorded",
sprintf("inside %d-%d", SPEC_LO, SPEC_HI),
"cap recorded", "cap passed")
kept <- c(nrow(bottles), nrow(step2), nrow(step3), nrow(step4), nrow(passed))
dropped <- c(0L, head(kept, -1) - tail(kept, -1))
rule36 <- strrep("-", 36)
writeLines(sprintf("%-20s%7s%9s", "STATION", "KEPT", "DROPPED"))
writeLines(rule36)
writeLines(sprintf("%-20s%7d%9d", stations, kept, dropped))
writeLines(rule36)
writeLines("")
reasons <- c("no weight", "underfill", "overfill", "cap unknown", "cap bad", "ok")
counts <- vapply(reasons, function(r) sum(tagged$reason == r), integer(1))
rule21 <- strrep("-", 21)
writeLines(sprintf("%-16s%5s", "REASON", "COUNT"))
writeLines(rule21)
writeLines(sprintf("%-16s%5d", reasons, counts))
writeLines(rule21)
writeLines(sprintf("%-16s%5d", "TOTAL", sum(counts)))
writeLines("")
ranked <- passed |> arrange(desc(fill), id)
cased <- ranked |> slice_head(n = CASE_N)
loose <- ranked |> slice_tail(n = nrow(ranked) - CASE_N)
writeLines(sprintf("%-7s%s", "CASE", "BOTTLES"))
writeLines(sprintf("%-7s%s", "C1", paste(cased$id, collapse = " ")))
writeLines(sprintf("%-7s%s", "LOOSE", paste(loose$id, collapse = " ")))
writeLines("")
cut_fill <- tail(cased$fill, 1)
both <- bottles |> filter(!is.na(fill), fill < SPEC_LO, !is.na(cap), !cap) |> pull(id)
at_cut <- passed |> filter(fill == cut_fill) |> pull(id)
recon <- counts[["ok"]] == nrow(passed) && sum(counts) == nrow(bottles) &&
nrow(cased) + nrow(loose) == nrow(passed)
writeLines(sprintf("%-18s: %d", "bottles in", nrow(bottles)))
writeLines(sprintf("%-18s: %d", "passed", nrow(passed)))
writeLines(sprintf("%-18s: %d", "rejected", nrow(bottles) - nrow(passed)))
writeLines(sprintf("%-18s: %d", "cased", nrow(cased)))
writeLines(sprintf("%-18s: %d", "loose", nrow(loose)))
writeLines(sprintf("%-18s: %s", "counts reconcile", recon))
writeLines(sprintf("%-18s: %d", "case fill ml", sum(cased$fill)))
writeLines(sprintf("%-18s: %.1f", "case mean ml", mean(cased$fill)))
writeLines(sprintf("%-18s: %d", "over nominal ml", sum(cased$fill) - NOMINAL * CASE_N))
writeLines(sprintf("%-18s: %.1f", "loose mean ml", mean(loose$fill)))
writeLines(sprintf("%-18s: %.1f", "run mean ml", mean(passed$fill)))
writeLines(sprintf("%-18s: L1 %d L2 %d", "passed by line",
sum(passed$line == "L1"), sum(passed$line == "L2")))
writeLines(sprintf("%-18s: %s", "skus in the run",
paste(sort(unique(bottles$sku)), collapse = " ")))
writeLines(sprintf("%-18s: %d", "skus in the case", n_distinct(cased$sku)))
writeLines(sprintf("%-18s: %s", "both faults", paste(both, collapse = " ")))
writeLines(sprintf("%-18s: %s", "tie at the cut", paste(at_cut, collapse = " ")))
Output:
STATION KEPT DROPPED
------------------------------------
records in 24 0
weight recorded 21 3
inside 495-505 17 4
cap recorded 16 1
cap passed 15 1
------------------------------------
REASON COUNT
---------------------
no weight 3
underfill 2
overfill 2
cap unknown 1
cap bad 1
ok 15
---------------------
TOTAL 24
CASE BOTTLES
C1 B04 B15 B01 B12 B23 B08 B24 B10 B19 B03 B20 B06
LOOSE B14 B17 B22
bottles in : 24
passed : 15
rejected : 9
cased : 12
loose : 3
counts reconcile : TRUE
case fill ml : 6014
case mean ml : 501.2
over nominal ml : 14
loose mean ml : 496.3
run mean ml : 500.2
passed by line : L1 8 L2 7
skus in the run : COLA LEMON TONIC
skus in the case : 3
both faults : B18
tie at the cut : B06 B14
The funnel is the report the plant asked for. Each row is one filter() and the DROPPED column is the difference between neighbouring row counts, so the four drops add up to the nine rejected bottles and nothing goes missing between the top and the bottom. It tells the supervisor that the weigher and the band test cost seven bottles between them while the capper cost two.
The reason tally answers the other question: not how many, but why. It is built from a fixed vector of reasons in severity order and a sum() over the tagged column, so the rows appear in the same order on every run and a reason with a count of zero is still printed. counts reconcile checks that the ok count equals the number of survivors and that the six counts add to 24: the tag and the chain describe the same shift independently, and they agree.
The packing list comes from arrange(desc(fill), id) followed by slice_head() and slice_tail(), which cannot lose a row because their counts are 12 and 3. The case holds 6014 ml against a nominal 6000, the loose bottles hold 1489 ml, and the two add to the 7503 ml that passed. tie at the cut exists because the twelfth and thirteenth bottles both hold 498 ml.
That tie is the first real flaw. The order of two equal bottles is decided by id, so B06 is cased and B14 is not for no reason connected to quality. The second flaw is worse: case_when() charges each bottle to its first matching clause, so B18, both underfilled and badly capped, is booked as underfill and cap bad reads 1 when two bottles failed a cap check -- exactly the number a maintenance manager would use to decide whether to strip the capper. Third, the packer takes the heaviest twelve, which is backwards for a plant paid to fill consistently; the honest key is abs(fill - NOMINAL). Fourth, the case ignores sku, so skus in the case is 3 and C1 is a mixed case no customer ordered. Fifth, the funnel counts come from re-running the chain into named intermediates, so adding a sixth check means editing both the chain and the stations vector, and nothing notices when only one is updated.
Common Mistakes
- Expecting
filter()to keep rows it could not judge. A condition that evaluates toNAis notTRUE, so those rows are dropped exactly like failures. Testis.na()first and count the unknowns separately.
- Writing a chain and never assigning it.
runs |> filter(line == "L1")builds a frame, prints it, and throws it away;runsis untouched. Every chain needs a name on the left or another verb on the right.
- Using
ifelse()when a missing value needs a label. It propagatesNAinto the result, so a column meant to holdINorOUTquietly gains a third value.if_else(cond, a, b, missing = "UNWEIGHED")names it.
- Ordering
case_when()clauses by convenience. First match wins, so a row with two faults is booked to whichever clause you typed first. The order is the policy; put the clause you want charged at the top.
- Assuming
desc()lifts missing values to the front.arrange()parksNAlast in both directions, so sorting descending to find the worst rows leaves the unmeasured ones at the bottom.
- Confusing
select(fill)withpull(fill). The first is a one-column frame, the second a vector. Feeding a frame tomean()fails or returns something strange, and the error names a line further down.
- Putting a bare variable inside
select().select(want)looks for a column literally calledwant. When the name is held in a variable it must beselect(all_of(want)), which also errors loudly if the column is absent.
- Handing the native placeholder to a positional argument.
x |> gsub("a", "b", _)is an error;_must go to a named argument, as inx = _. Magrittr's.has no such rule, so code copied between the two pipes breaks.
- Trusting
slice_max(n = 1)to return one row. Ties are kept by default, so a tie at the top returns two rows and any count built on it is off by one. Passwith_ties = FALSEfor exactlyn.
Best Practices
- Put one verb per line with the pipe at the end, so a chain reads as a list of steps and any single step can be commented out while you test.
- Name the intermediates you need to report on. The funnel above only exists because
step2throughpassedhave names; one unbroken chain cannot say where the rows went.
- Deal with missingness explicitly before you filter on a value. Count the unknowns, label them, or drop them on purpose, but do not let
filter()fold them in with the failures.
- Order
case_when()clauses by severity and say so in a comment, because the next reader cannot tell a deliberate order from an accidental one.
- Prefer
between(x, lo, hi)to a pair of comparisons for an inclusive band; it names the column once and cannot pick up a typo in the second bound.
- Reach for
if_else()overifelse(). The type strictness catches a mixed branch where the mistake is, andmissing =turns an unknown into a value you chose.
- Use
pull()only at the end of a chain, where you genuinely want to leave the world of frames and hand a vector to something else.
- Print a reconciliation line. One
TRUEtying the parts back to the total beats any amount of eyeballing, and it fails loudly when the data changes shape.
Practice Exercises
- Replace the packing rule so the case takes the twelve bottles closest to
NOMINALinstead of the heaviest twelve, breaking ties byid. Print the new case, its mean fill, and the difference between the two rules'over nominal mlfigures.
- Fix the double-fault undercount without abandoning
case_when(). Add a column per fault, then print how many bottles failed each check independently alongside the single-reason tally, and state which cell the two disagree about.
- Rewrite the funnel so it is driven by a list of named conditions rather than four hand-written intermediates, recording the row count after each. The printed table must be identical to the one above.
- Add a per-
skucase rule: no case may hold more than onesku. Report how many complete cases of twelve the shift can fill, how many bottles are left over, and whichskuwastes the most.