The Analogy: The Joinery's Pattern Jig and Gang Press
A bench joiner making one door works by eye and by rule: marking gauge, try square, pencil line, saw. Making twenty identical doors that way is a different job, and no joiner attempts it, because twenty sets of pencil lines produce twenty slightly different doors. Instead the joiner spends the first hour building a jig: a plywood template with a fence along one edge and two stops screwed to it, cut once and checked once. Every stile afterwards goes against the fence and up to the stop. That hour is not overhead; the jig is the one place where the measurement is decided, so it is the one place where it can be wrong.
At the far end of the shop there is a gang press: a bed with a row of fixtures and one long handle. The operator lays a whole batch into the fixtures, pulls the handle once, and every part is pressed in the same stroke. Nothing about the press is faster per part than a hand clamp. What it removes is the loading, aligning and checking a hand clamp needs on every single part. The operator does not stand there pressing parts one at a time with a tally in their head; the batch goes in and the batch comes out.
The jig's stops are where the shop's discipline lives. The near stop is fixed, because every part shares that reference face; the far stop moves, because that is the dimension that changes between a stile and a rail. Screwed to the side is a card giving the settings the jig was cut for. An apprentice who wants a rail moves one stop and leaves the rest alone, without needing to understand the whole jig. That is the entire value of a written default: it turns the common case into a single decision rather than a full setup.
The press hurts the shop through its output tray. The tray is a slotted rack sized for one part shape, and it works perfectly while every part in the batch is that shape. Put a batch through where one part is a different thickness and the rack no longer stacks: the next bench receives a jumbled pile instead of a neat stack, and nothing announced it, because the handle came down exactly as it always does. The parts are all correct. The container is wrong, and the container is what gets passed on -- and a pile still looks like output, so it travels one bench further before anyone notices. A shop bitten by this once stops asking the tray what shape the batch is, and starts declaring the shape before the handle comes down.
Syntax or Core Structure
A function in R is an ordinary value with a formal argument list, a body and an environment, and it can be stored in a list, passed to another function, or returned from one. The last expression evaluated in the body is the return value, so return() is for leaving early rather than a required piece of syntax. Arguments are matched by exact name first, then partial name, then position, which is why naming an argument at the call site is the only way to be certain which slot it landed in. Defaults are expressions evaluated lazily inside the function's own frame, so a default can refer to another argument and is not computed at all if the caller supplies the value.
bmi <- function(weight_kg, height_m, dp = 1) {
round(weight_kg / height_m^2, dp)
}
step <- function(n, label = paste0("step-", n)) {
label
}
quiet <- function(x) {
doubled <- x * 2
}
v <- quiet(5)
vis <- withVisible(quiet(5))
writeLines(sprintf("%-14s: %.1f", "positional", bmi(70, 1.75)))
writeLines(sprintf("%-14s: %.1f", "named", bmi(height_m = 1.75, weight_kg = 70)))
writeLines(sprintf("%-14s: %.3f", "dp = 3", bmi(70, 1.75, dp = 3)))
writeLines(sprintf("%-14s: %s", "lazy default", step(4)))
writeLines(sprintf("%-14s: %d", "last value", as.integer(v)))
writeLines(sprintf("%-14s: %s", "was it visible", vis$visible))
Output:
positional : 22.9
named : 22.9
dp = 3 : 22.857
lazy default : step-4
last value : 10
was it visible: FALSE
The first two lines are one call written two ways: reordering the arguments changed nothing because both were named. The third overrides the default, and the fourth shows a default reading another argument, so step(4) yields step-4 without the caller mentioning a label. The last two lines are the trap worth learning early -- quiet ends in an assignment, and assignment returns invisibly, so the function does return 10 but printing the call at the console shows nothing. The value is there; only the printing was suppressed.
Technical Depth: What the Family Returns, and When It Changes Its Mind
Every member of the apply family answers the same question -- run this function over this collection -- and they differ almost entirely in what container they hand back. Choosing the wrong member rarely produces a wrong number. It produces a right number in a container the next line was not written for.
The family, member by member
| Call | What it feeds the function | What it hands back |
|---|---|---|
lapply(x, f) | each element of x in turn | a list, always, of the same length as x |
sapply(x, f) | the same | a vector, a matrix, or a list, decided at run time |
vapply(x, f, FUN.VALUE) | the same | exactly the shape declared in FUN.VALUE, or an error |
mapply(f, a, b) | elements of several arguments in step | simplified by the same rules as sapply |
Map(f, a, b) | the same | a list, always |
apply(m, 1, f) | each row of a matrix or array | simplified, with results as columns |
Reduce(f, x) | two values at a time, left to right | one accumulated value |
do.call(f, x) | the whole list at once, as the argument list | whatever a single call to f returns |
The two worth committing to memory are the extremes. lapply is the honest one: it makes no attempt to be clever, so its result type never depends on the data. vapply is the strict one: you state the shape of one result up front and it checks every result against that statement. sapply sits between them and ships the bugs, because it is a call to lapply followed by a guess.
sapply decides the shape from the data
sapply inspects the results after the fact. If every result has length one it unlists them into a vector; if every result has the same length greater than one it builds a matrix with one column per input element; if the lengths differ at all it gives up and returns the list lapply produced. Three return types from one function, selected by data the author of the calling code has never seen.
one <- sapply(1:3, function(i) i * 2)
pair <- sapply(1:3, function(i) c(i, i * i))
ragged <- sapply(1:3, seq_len)
strict <- vapply(1:3, function(i) i * 2, numeric(1))
bad <- try(vapply(1:3, seq_len, numeric(1)), silent = TRUE)
shape <- function(x) if (is.null(dim(x))) "none" else paste(dim(x), collapse = " x ")
writeLines(sprintf("%-17s: %s", "scalar class", class(one)[1]))
writeLines(sprintf("%-17s: %s", "scalar dim", shape(one)))
writeLines(sprintf("%-17s: %s", "pair class", class(pair)[1]))
writeLines(sprintf("%-17s: %s", "pair dim", shape(pair)))
writeLines(sprintf("%-17s: %s", "ragged class", class(ragged)[1]))
writeLines(sprintf("%-17s: %d", "ragged length", length(ragged)))
writeLines(sprintf("%-17s: %s", "vapply scalar", paste(strict, collapse = " ")))
writeLines(sprintf("%-17s: %s", "vapply ragged", if (inherits(bad, "try-error")) "errored" else "passed"))
Output:
scalar class : numeric
scalar dim : none
pair class : matrix
pair dim : 2 x 3
ragged class : list
ragged length : 3
vapply scalar : 2 4 6
vapply ragged : errored
Note the orientation of pair: the function returned two values for each of three inputs and the matrix is 2 by 3, not 3 by 2, because results become columns. The last two lines are the whole argument for vapply: the ragged input that made sapply quietly change container made vapply stop, at the mistake rather than three functions later.
Declaring the shape before the handle comes down
The third argument to vapply is not a type name, it is a specimen: a value of exactly the length and class every result must have. Give it numeric(1) and you have promised one number per element; give it c(min = 0, max = 0) and you have promised two named numbers, and those names become the result's row names. The specimen is documentation the interpreter enforces.
apply is the odd member, working on the margins of a matrix rather than the elements of a list, and its results come back as columns whichever margin you walked. Walk the rows of a 3-by-2 matrix with a function returning two values and the result is 2 by 3. That is a consequence of R filling matrices column-first, and it is not going to change.
lens <- list(a = c(1, 2, 3), b = c(10, 20, 30))
span <- vapply(lens, function(v) c(min = min(v), max = max(v)), c(min = 0, max = 0))
m <- matrix(1:6, nrow = 3)
doubled <- apply(m, 1, function(r) r * 2)
tags <- c(a = 1, b = 2, c = 3)
paired <- Map(function(k, v) paste0(k, "=", v), names(tags), tags)
writeLines(sprintf("%-17s: %s", "vapply dim", paste(dim(span), collapse = " x ")))
writeLines(sprintf("%-17s: %s", "vapply rows", paste(rownames(span), collapse = " ")))
writeLines(sprintf("%-17s: %s", "vapply cols", paste(colnames(span), collapse = " ")))
writeLines(sprintf("%-17s: %d", "b max", as.integer(span["max", "b"])))
writeLines(sprintf("%-17s: %s", "input dim", paste(dim(m), collapse = " x ")))
writeLines(sprintf("%-17s: %s", "apply dim", paste(dim(doubled), collapse = " x ")))
writeLines(sprintf("%-17s: %s", "apply transposed", identical(dim(doubled), rev(dim(m)))))
writeLines(sprintf("%-17s: %s", "Map names", paste(names(paired), collapse = " ")))
writeLines(sprintf("%-17s: %s", "Map values", paste(unlist(paired), collapse = " ")))
writeLines(sprintf("%-17s: %s", "Map class", class(paired)))
Output:
vapply dim : 2 x 2
vapply rows : min max
vapply cols : a b
b max : 30
input dim : 3 x 2
apply dim : 2 x 3
apply transposed : TRUE
Map names : a b c
Map values : a=1 b=2 c=3
Map class : list
Map is the two-collection walk, and it is mapply with simplification switched off. It takes names from its first argument, which is why passing names(tags) first gives a list keyed by name -- the standard way to reach a name and its value in the same iteration without indexing either. Using seq_along and subscripting both vectors works too, and is one more place for an off-by-one to live.
Folding with Reduce, and spreading with do.call
Reduce collapses a collection to a single value by applying a two-argument function repeatedly, left to right, carrying the result forward. do.call does the opposite: it takes a list and uses it as the argument list of one call. Between them they cover the two cases mapping cannot -- an accumulation where each step depends on the last, and a function that wants all the values at once.
rows <- list(c(1, 2), c(3, 4), c(5, 6))
folded <- Reduce("+", 1:5)
running <- Reduce("+", 1:5, accumulate = TRUE)
joined <- Reduce(function(a, b) paste0(a, ">", b), c("saw", "plane", "sand"))
stacked <- do.call(rbind, rows)
writeLines(sprintf("%-17s: %d", "sum fold", folded))
writeLines(sprintf("%-17s: %s", "running fold", paste(running, collapse = " ")))
writeLines(sprintf("%-17s: %s", "string fold", joined))
writeLines(sprintf("%-17s: %d", "do.call sum", as.integer(do.call(sum, list(1, 2, 3)))))
writeLines(sprintf("%-17s: %s", "rbind dim", paste(dim(stacked), collapse = " x ")))
writeLines(sprintf("%-17s: %d", "rbind col 2 sum", as.integer(sum(stacked[, 2]))))
writeLines(sprintf("%-17s: %s", "empty fold null", is.null(Reduce("+", list()))))
writeLines(sprintf("%-17s: %d", "empty with init", as.integer(Reduce("+", list(), 0))))
Output:
sum fold : 15
running fold : 1 3 6 10 15
string fold : saw>plane>sand
do.call sum : 6
rbind dim : 3 x 2
rbind col 2 sum : 12
empty fold null : TRUE
empty with init : 0
The last two lines are the reason to supply init even when it looks redundant. A fold over an empty collection has no answer unless you have said what zero means, so Reduce returns NULL -- and NULL flows onward into arithmetic that yields a zero-length result rather than an error. With init = 0 the empty case returns the identity and the pipeline keeps its type. Empty input never appears during development and always appears in production.
Real World Example: A Joinery Cut List and Board Yield
A joinery shop has a cut list for a run of cabinet doors and a stack of 2400 mm boards. The job is to decide how many boards to draw from the rack, which parts come off which board, and how much timber ends up as offcut. Every saw cut consumes 3 mm as sawdust, so the kerf is consumption rather than a rounding error. The packing decision is a fold -- each part is placed against the boards opened so far -- and everything after it is a mapping.
CAP <- 2400L
KERF <- 3L
cutlist <- data.frame(code = c("STILE", "RAIL", "MULLION", "SHELF", "PLINTH"), off = c(4L, 4L, 2L, 3L, 1L), len = c(900L, 520L, 780L, 1140L, 1980L), stringsAsFactors = FALSE)
pieces <- data.frame(code = rep(cutlist$code, cutlist$off), len = rep(cutlist$len, cutlist$off), stringsAsFactors = FALSE)
pieces <- pieces[order(-pieces$len, pieces$code), ]
place <- function(boards, i) {
need <- pieces$len[i] + KERF
fits <- vapply(boards, function(b) b$free >= need, logical(1))
k <- if (any(fits)) which(fits)[1] else length(boards) + 1L
if (k > length(boards)) {
boards[[k]] <- list(free = CAP, codes = character(0), lens = integer(0))
}
boards[[k]]$free <- boards[[k]]$free - need
boards[[k]]$codes <- c(boards[[k]]$codes, pieces$code[i])
boards[[k]]$lens <- c(boards[[k]]$lens, pieces$len[i])
boards
}
boards <- Reduce(place, seq_len(nrow(pieces)), init = list())
ids <- paste0("B", seq_along(boards))
per <- vapply(boards, function(b) c(pieces = length(b$lens), cut = sum(b$lens), kerf = KERF * length(b$lens), offcut = b$free), c(pieces = 0L, cut = 0L, kerf = 0L, offcut = 0L))
colnames(per) <- ids
tot <- as.integer(rowSums(per))
names(tot) <- rownames(per)
stock <- CAP * length(boards)
writeLines(sprintf("%-7s%7s%8s%6s%8s%7s", "BOARD", "PIECES", "CUT_MM", "KERF", "OFFCUT", "FILL%"))
writeLines(strrep("-", 43))
writeLines(vapply(seq_along(ids), function(j) sprintf("%-7s%7d%8d%6d%8d%7.1f", ids[j], per["pieces", j], per["cut", j], per["kerf", j], per["offcut", j], 100 * per["cut", j] / CAP), character(1)))
writeLines(strrep("-", 43))
writeLines(sprintf("%-7s%7d%8d%6d%8d%7.1f", "TOTAL", tot[["pieces"]], tot[["cut"]], tot[["kerf"]], tot[["offcut"]], 100 * tot[["cut"]] / stock))
writeLines("")
writeLines(sprintf("%-7s%s", "BOARD", "CONTENTS"))
writeLines(vapply(seq_along(boards), function(j) sprintf("%-7s%s", ids[j], paste(boards[[j]]$codes, collapse = " ")), character(1)))
writeLines("")
by_len <- split(pieces$len, pieces$code)
part_n <- vapply(by_len, length, integer(1))
part_each <- vapply(by_len, function(v) {
stopifnot(length(unique(v)) == 1L)
v[1]
}, integer(1))
part_tot <- vapply(by_len, sum, integer(1))
writeLines(sprintf("%-10s%5s%7s%8s", "PART", "OFF", "EACH", "TOTAL"))
writeLines(vapply(names(by_len), function(nm) sprintf("%-10s%5d%7d%8d", nm, part_n[[nm]], part_each[[nm]], part_tot[[nm]]), character(1)))
writeLines("")
w <- which.max(per["offcut", ])
ok <- isTRUE(all.equal(tot[["cut"]] + tot[["kerf"]] + tot[["offcut"]], stock))
writeLines(sprintf("%-17s: %d", "pieces cut", tot[["pieces"]]))
writeLines(sprintf("%-17s: %d", "piece mm", tot[["cut"]]))
writeLines(sprintf("%-17s: %d", "kerf mm", tot[["kerf"]]))
writeLines(sprintf("%-17s: %d", "offcut mm", tot[["offcut"]]))
writeLines(sprintf("%-17s: %d", "stock mm", stock))
writeLines(sprintf("%-17s: %s", "mm reconciles", ok))
writeLines(sprintf("%-17s: %.1f", "yield pct", 100 * tot[["cut"]] / stock))
writeLines(sprintf("%-17s: %s %d", "worst offcut", ids[w], per["offcut", w]))
writeLines(sprintf("%-17s: %d", "boards needed", length(boards)))
Output:
BOARD PIECES CUT_MM KERF OFFCUT FILL%
-------------------------------------------
B1 1 1980 3 417 82.5
B2 2 2280 6 114 95.0
B3 2 2040 6 354 85.0
B4 3 2320 9 71 96.7
B5 3 2200 9 191 91.7
B6 3 1820 9 571 75.8
-------------------------------------------
TOTAL 14 12640 42 1718 87.8
BOARD CONTENTS
B1 PLINTH
B2 SHELF SHELF
B3 SHELF STILE
B4 STILE STILE RAIL
B5 STILE MULLION RAIL
B6 MULLION RAIL RAIL
PART OFF EACH TOTAL
MULLION 2 780 1560
PLINTH 1 1980 1980
RAIL 4 520 2080
SHELF 3 1140 3420
STILE 4 900 3600
pieces cut : 14
piece mm : 12640
kerf mm : 42
offcut mm : 1718
stock mm : 14400
mm reconciles : TRUE
yield pct : 87.8
worst offcut : B6 571
boards needed : 6
Read the program as three jobs joined by data. The first expands the cut list into one row per physical piece with rep and sorts it longest first: order(-len, code) breaks ties by part code, which matters because two orderings of equal-length pieces give different board contents and the report would not say which one you got. The second is place, a function from a state and one piece to a new state, handed to Reduce; there is no accumulator variable and no loop counter, because the fold owns both. The third is pure mapping -- vapply with a four-element integer specimen turns the list of boards into a 4-by-6 matrix, and every report line after that is a vapply producing strings for writeLines.
The board table reads as one board's story per row. B1 holds the 1980 mm plinth and nothing fits beside it, so it wastes 417 mm and fills to only 82.5 per cent. B4 is the best-packed board at 96.7 per cent, with 71 mm no part in this job could use. B6 is the tail of the run, and its 571 mm offcut is the largest piece of usable timber the job leaves behind, which is what a joiner wants flagged: it goes back on the rack as short stock rather than into the bin.
The line worth trusting is mm reconciles. Every millimetre drawn from the rack is in exactly one of three places: it became a part, it became sawdust, or it is still attached to an offcut. So 12640 plus 42 plus 1718 must equal six boards at 2400 mm, and it does. That one identity catches the whole class of errors this code attracts -- a piece added to a board's contents but not subtracted from its remaining length, a kerf charged twice -- and none of those would make the report look wrong.
The limits are real, and the first is a defect rather than a simplification. Nothing in place asserts that a piece fits the board it ends up on: when no open board has room the function opens a fresh one and places the piece unconditionally, so a part of exactly 2400 mm -- which needs 2403 mm once its kerf is charged -- lands on a new board, produces a negative free, and is reported as a negative offcut beside a fill of 100 per cent instead of being rejected as uncuttable from this stock. The kerf model errs the same way: the last cut on a board separates the final part from the offcut, so charging a kerf per piece bills one cut too many per board, 18 mm across this job. First-fit decreasing is also only a heuristic, and the program never computes the volume bound that would say whether six boards is optimal -- here 12682 mm over 2400 mm boards needs at least six, so it happens to be, but the code cannot say so. And the model is one-dimensional: width, thickness, grain and board defects do not appear, so two stiles the report takes from one board may be unusable as a matched pair.
Common Mistakes
- Using
sapplyanywhere other than the console. Its return type is chosen from the results, so the same line gives a vector today and a list tomorrow when one element of the input changes length. The failure surfaces in whatever consumes the result, not at thesapplycall.
- Ending a function body with an assignment and expecting a printable result. Assignment returns invisibly, so the function does return the number but nothing appears at the console. People then add a
print()inside the body, which makes the function print on every call.
- Accumulating into an outer variable with the double arrow inside
lapply. The point of a mapping function is that each call is independent and the results come back as a value. Reaching out of the frame reintroduces order dependence and makes the mapped function untestable alone.
- Defining functions inside a
forloop and expecting each to capture that iteration's value. The loop assigns to one variable in one environment, so every function reads the value left after the last pass -- three built with multipliers 1, 2 and 3 all multiply by 3.lapplygives each its own frame.
- Calling
applyon a data frame.applyworks on matrices, so it silently runsas.matrixfirst. One character column turns every value into a string, and row sums either error or return nonsense. Uselapplyover columns, orrowSumson columns you chose deliberately.
- Writing a
vapplytemplate of the wrong type.1is a double, sovapply(x, nchar, 1)promises doubles whereinteger(1)would have kept integers. Printing hides the difference andidenticaldoes not, which is how a test starts failing for no visible reason.
- Assuming an empty input gives an empty vector.
sapplyover a zero-length input returnslist(), notnumeric(0), and arithmetic on a list is an error rather than a zero.vapplyreturns a properly typed empty vector, which is one more reason to prefer it.
- Leaving
SIMPLIFYat its default inmapply. It runs the same shape lottery assapply, on results you control even less because they come from several inputs walked in step. UseMapwhen you want a list.
- Trusting argument names forwarded through
.... A misspelled name in a direct call is an error, but one passed through...into a function that also takes...is quietly absorbed, so the option you thought you set was never applied and nothing said so.
Best Practices
- Reach for
vapplyby default,lapplywhen results genuinely differ in shape, andsapplyonly at the console where you can see what came back.
- Write the
FUN.VALUEspecimen with the type you actually want, usinginteger(1)orcharacter(1)rather than0or"", so the declaration covers type as well as length.
- Give each function one job and a verb for a name. If the name needs an "and" in it, it is two functions.
- Put defaults in the signature rather than testing for a missing argument in the body: the signature is the part of the function that gets read.
- Return values instead of reaching out of the frame. Keep the double arrow for a deliberate factory, where the state it writes to is state you created.
- Walk two collections with
Mapormapplyrather than indexing both by position, and let the names come from the first argument.
- Give
Reducean explicitinitso the empty case has a defined answer, and prefer a plain loop when the reader needs to watch the order of the steps.
- Assert your assumptions at the top with
stopifnot, so a violated one fails by name instead of surfacing as a strange number several calls later.
Practice Exercises
- Fix the fit defect in
place. Make it refuse any piece that cannot fit an empty board, collecting rejects in a second element of the accumulator, and prove the millimetre reconciliation still holds over the pieces that were placed.
- Correct the kerf model so the final cut on each board is not charged, since it separates the last part from the offcut. Report how the kerf total, the offcut total and the board count change, and confirm the three figures still sum to the stock drawn.
- Write a
shape_ofhelper returning a one-line description of any result, then use it to comparelapply,sapplyandvapplyover three inputs: one where every result is a scalar, one where every result has length two, and one ragged. Print the nine outcomes as a fixed-width table.
- Replace the first-fit rule in
placewith best-fit, choosing the open board whose remaining length is smallest but still sufficient. Report both yields, and say whether the board count changed for this cut list.