The Analogy: The Records Office Concertina Folder
Behind the counter of a records office stands a concertina folder -- a stiff card wallet that opens out into a row of deep pockets, each with a tab written along its top edge. The pocket marked CORRESPONDENCE holds a thick bundle of letters. The pocket marked PHOTOGRAPH holds one glass plate and nothing else. The pocket marked SUB-FILE holds another, smaller concertina folder with pockets of its own. The pocket marked FLAG holds a single card with the word YES on it. Nothing about the folder requires its pockets to hold the same kind of thing, or the same number of things, and that is exactly why the office uses one. A card-index drawer next to it can only hold cards, all the same size, all the same kind. The concertina folder holds whatever the case needed.
There are two quite different ways to get something out of it, and the office staff are careful about which one they mean. You can grip a pocket by its top edge and lift the whole pocket out of the folder: what you are now holding is still a pocket, with its tab still written on it, and it happens to contain the letters. That is single-bracket retrieval. Or you can hold the folder open with one hand, reach into the pocket, and draw out the bundle of letters itself: now you are holding letters, and the pocket has stayed in the folder. That is double-bracket retrieval. There is also a third way, which is to lean over the counter and say a tab name to the clerk, who reaches in and hands you the contents. That is the dollar operator, and the clerk is quick but not careful.
Because a pocket may itself contain a folder, getting to a document can take several steps, each one naming the next tab down: open the outer folder, reach into SUB-FILE, and from the smaller folder inside reach into AUDIT, and from there draw out the single card marked SHIFT. The tabs are the only navigation the folder offers. A pocket whose tab was never written on can still be counted to -- third from the left -- but nobody coming to the folder cold will ever find it on purpose, and if somebody inserts a new pocket at the front, every count anyone wrote down becomes wrong.
The failures are all failures of the same kind: you get handed something plausible instead of what you asked for. The commonest is being handed the pocket when you wanted the letters. It looks right in your hand, it has the correct tab on it, and you only discover the mistake when you put it on the copier and get a photograph of an empty cardboard sleeve. The second is the quick clerk. Ask for COEF and the clerk, seeing only one tab that starts that way, cheerfully hands you the contents of COEFFICIENTS -- which is what you meant, until the day somebody adds a COEFFICIENT_NOTES pocket and the same request stops working, or worse, quietly starts returning the notes. The third is the missing tab. Ask for a tab that is not on the folder and the clerk does not say "no such pocket"; the clerk hands you nothing at all, with the same untroubled expression, and you walk away carrying an emptiness that will not announce itself until three steps later. And the fourth is the empty pocket: a tab that exists, is correctly named, and contains nothing. Every question you ask of its contents comes back satisfied. Were all the documents in it accounted for? Yes, all of them. How many were damaged? None. An empty pocket passes every check a full one would, which is how a request for nothing gets filed as a request completely fulfilled.
Syntax or Core Structure
A list is built with list(), and unlike c() it does not flatten and does not coerce. Each argument becomes one pocket, keeping whatever type and length it arrived with, and the argument name becomes the tab.
model <- list(
name = "Linear Regression",
coefficients = c(2.5, -1.2, 0.4),
converged = TRUE,
metadata = list(date = "2023-10-27", author = "Alice")
)
cat(sprintf("length : %d\n", length(model)))
cat(sprintf("names : %s\n", paste(names(model), collapse = " ")))
cat(sprintf("class of x : %s\n", class(model["coefficients"])))
cat(sprintf("class of xx : %s\n", class(model[["coefficients"]])))
cat(sprintf("name : %s\n", model$name))
cat(sprintf("converged : %s\n", model[["converged"]]))
cat(sprintf("coefs : %s\n", paste(model$coefficients, collapse = " ")))
cat(sprintf("nested date : %s\n", model$metadata$date))
cat(sprintf("depth-2 auth: %s\n", model[["metadata"]][["author"]]))
cat(sprintf("missing tab : %s\n", is.null(model$slope)))
Output:
length : 4
names : name coefficients converged metadata
class of x : list
class of xx : numeric
name : Linear Regression
converged : TRUE
coefs : 2.5 -1.2 0.4
nested date : 2023-10-27
depth-2 auth: Alice
missing tab : TRUE
The two class lines are the whole lesson in miniature. model["coefficients"] lifts the pocket out and hands you a list of length one that happens to contain three numbers. model[["coefficients"]] reaches inside and hands you the three numbers. Both expressions are legal, both look almost identical on the page, and only the second one can be passed to mean.
Note also the last line. Asking for a tab that does not exist is not an error. model$slope returns NULL, and so does model[["slope"]]. The absence is a value, and a value travels.
Technical Depth: Three Accessors, Deletion, and Flattening
The accessor table
Three pieces of syntax reach into a list, and they differ in what they return, what they do when the name is absent, and whether they will accept an abbreviation.
| Accessor | Returns | When the name is absent | Partial matching |
|---|---|---|---|
x["a"] | a length-one list, tab kept | a length-one list holding NULL | never |
x[["a"]] | the object inside the pocket | NULL | only with exact = FALSE |
x$a | the object inside the pocket | NULL | yes, and silently |
x[[2]] | the object in the second pocket | subscript out of bounds error | not applicable |
The row that costs people the most time is the third one. Partial matching on the dollar operator is a convenience for typing at the console that becomes a defect the moment the list grows a second tab with the same prefix.
model <- list(coefficients = c(2.5, -1.2, 0.4), converged = TRUE)
cat(sprintf("dollar partial : %s\n", paste(model$coef, collapse = " ")))
cat(sprintf("brkt exact : %s\n", is.null(model[["coef"]])))
cat(sprintf("brkt inexact : %s\n", paste(model[["coef", exact = FALSE]], collapse = " ")))
cat(sprintf("single brkt : %s\n", class(model["coefficients"])))
cat(sprintf("single len : %d\n", length(model["coefficients"])))
cat(sprintf("dbl len : %d\n", length(model[["coefficients"]])))
Output:
dollar partial : 2.5 -1.2 0.4
brkt exact : TRUE
brkt inexact : 2.5 -1.2 0.4
single brkt : list
single len : 1
dbl len : 3
The dollar operator resolved coef to coefficients without comment. Double brackets refused, returning NULL, until explicitly told not to be exact. That refusal is the reason [[ belongs in code you intend to keep and $ belongs at the console.
Assigning NULL deletes the pocket
Assignment into a list is where the pocket metaphor earns its keep, because R distinguishes removing a pocket from putting an empty pocket back.
cfg <- list(host = "shed-01", port = 8080L, retries = 3L)
cfg$timeout <- 30L
cfg[["port"]] <- 9090L
cfg$retries <- NULL
cat(sprintf("names : %s\n", paste(names(cfg), collapse = " ")))
cat(sprintf("length : %d\n", length(cfg)))
cat(sprintf("port : %d\n", cfg$port))
cfg["timeout"] <- list(NULL)
cat(sprintf("after : %s\n", paste(names(cfg), collapse = " ")))
cat(sprintf("held : %s\n", is.null(cfg$timeout)))
cat(sprintf("still : %d\n", length(cfg)))
Output:
names : host port timeout
length : 3
port : 9090
after : host port timeout
held : TRUE
still : 3
Three pockets went in, one was added, one was replaced, and one was removed, so three remain. The last three lines are the subtle part: cfg["timeout"] <- list(NULL) stores an actual NULL in an existing pocket, so is.null reports TRUE and the length is still three. Had that been written cfg$timeout <- NULL, the pocket would have been thrown away and the length would be two. The two spellings differ by one word and mean opposite things.
Flattening throws the folder away
unlist empties every pocket into one pile. Because the pile has to be a single atomic vector, every value is coerced up the ladder to the widest type present, and the tabs survive only as mangled name strings.
mixed <- list(a = 1L, b = "two", c = TRUE)
flat <- unlist(mixed)
cat(sprintf("flat class : %s\n", class(flat)))
cat(sprintf("flat values : %s\n", paste(flat, collapse = " ")))
cat(sprintf("flat names : %s\n", paste(names(flat), collapse = " ")))
nested <- list(x = 1:2, y = list(z = 3:4))
fn <- unlist(nested)
cat(sprintf("deep names : %s\n", paste(names(fn), collapse = " ")))
cat(sprintf("deep values : %s\n", paste(fn, collapse = " ")))
cat(sprintf("was a list : %s\n", is.list(nested)))
cat(sprintf("now a list : %s\n", is.list(fn)))
cat(sprintf("len before : %d\n", length(nested)))
cat(sprintf("len after : %d\n", length(fn)))
Output:
flat class : character
flat values : 1 two TRUE
flat names : a b c
deep names : x1 x2 y.z1 y.z2
deep values : 1 2 3 4
was a list : TRUE
now a list : FALSE
len before : 2
len after : 4
The integer 1 and the logical TRUE both became text, because one pocket held a string. The nesting became a naming convention: y.z1 is a name, not a path, and nothing will take you back to the two-level structure it came from. Length went from two pockets to four values. unlist is the right tool for turning a list of same-typed scalars into a vector and the wrong tool for almost everything else.
A data frame is a list wearing a class attribute
This is worth seeing now rather than in the next lesson, because it explains why so much list vocabulary works on tables.
patients <- data.frame(id = 1:3, temp = c(38.1, 37.2, 39.4))
cat(sprintf("is.list : %s\n", is.list(patients)))
cat(sprintf("length : %d\n", length(patients)))
cat(sprintf("ncol : %d\n", ncol(patients)))
cat(sprintf("names : %s\n", paste(names(patients), collapse = " ")))
cat(sprintf("class : %s\n", class(patients)))
cat(sprintf("second col : %s\n", paste(patients[[2]], collapse = " ")))
cat(sprintf("stripped : %s\n", class(unclass(patients))))
Output:
is.list : TRUE
length : 2
ncol : 2
names : id temp
class : data.frame
second col : 38.1 37.2 39.4
stripped : list
length on a data frame returns the column count, not the row count, because the underlying object is a list of two pockets and each pocket holds a column. Strip the class attribute and what is left is a plain list. Every rule above about [ versus [[ therefore applies to data frames too, which is why df["temp"] is a one-column table and df[["temp"]] is a numeric vector.
Real World Example: A Records Office Retrieval Log
Four dockets came over the counter this morning. Each one names a clerk, lists the pockets that were asked for, and carries a small audit stub recording which shift took it and whether a supervisor countersigned. The pocket lists are different lengths -- one docket asks for two, one for three, one for none at all -- and the audit stub is a record in its own right rather than a single value. No rectangular table can hold that shape without padding, so the natural structure is a list of lists, and the report is a walk over it.
inventory <- c("A1", "A2", "B1", "B2", "B3", "C1")
requests <- list(
list(docket = "R-1041", clerk = "HALE", pockets = c("A1", "B2"),
audit = list(shift = "EARLY", checked = TRUE)),
list(docket = "R-1042", clerk = "OKORO", pockets = c("B1", "B3", "C1"),
audit = list(shift = "EARLY", checked = TRUE)),
list(docket = "R-1043", clerk = "HALE", pockets = c("A2", "D9"),
audit = list(shift = "LATE", checked = FALSE)),
list(docket = "R-1044", clerk = "VANCE", pockets = character(0),
audit = list(shift = "LATE", checked = TRUE))
)
hdr_fmt <- "%-7s%-7s%6s%6s%8s%7s%6s%8s\n"
row_fmt <- "%-7s%-7s%6d%6d%8d%7s%6s%8s\n"
tot_fmt <- "%-14s%6d%6d%8d\n"
rule <- strrep("-", 55)
cat(sprintf(hdr_fmt, "DOCKET", "CLERK", "ASKED", "FOUND",
"MISSING", "SHIFT", "CHK", "STATUS"))
cat(rule, "\n", sep = "")
asked_all <- integer(0)
found_all <- integer(0)
clerk_all <- character(0)
short_ids <- character(0)
ok_count <- 0L
for (req in requests) {
pockets <- req[["pockets"]]
hits <- pockets %in% inventory
asked <- length(pockets)
found <- sum(hits)
missing <- asked - found
status <- if (missing > 0L) "SHORT" else "OK"
if (status == "OK") ok_count <- ok_count + 1L
if (status == "SHORT") short_ids <- c(short_ids, req[["docket"]])
asked_all <- c(asked_all, asked)
found_all <- c(found_all, found)
clerk_all <- c(clerk_all, req[["clerk"]])
cat(sprintf(row_fmt, req[["docket"]], req[["clerk"]],
asked, found, missing,
req[["audit"]][["shift"]],
as.character(req[["audit"]][["checked"]]),
status))
}
cat(rule, "\n", sep = "")
cat(sprintf(tot_fmt, "TOTAL", sum(asked_all), sum(found_all),
sum(asked_all) - sum(found_all)))
by_clerk <- table(clerk_all)
cat("\n")
cat(sprintf("%-7s%4s\n", "CLERK", "REQS"))
for (nm in names(by_clerk)) {
cat(sprintf("%-7s%4d\n", nm, by_clerk[[nm]]))
}
cat("\n")
cat(sprintf("short dockets : %s\n", paste(short_ids, collapse = ", ")))
cat(sprintf("all satisfied : %d of %d\n", ok_count, length(requests)))
Output:
DOCKET CLERK ASKED FOUND MISSING SHIFT CHK STATUS
-------------------------------------------------------
R-1041 HALE 2 2 0 EARLY TRUE OK
R-1042 OKORO 3 3 0 EARLY TRUE OK
R-1043 HALE 2 1 1 LATE FALSE SHORT
R-1044 VANCE 0 0 0 LATE TRUE OK
-------------------------------------------------------
TOTAL 7 6 1
CLERK REQS
HALE 2
OKORO 1
VANCE 1
short dockets : R-1043
all satisfied : 3 of 4
Look first at what only a list could carry. pockets is a character vector of length two, three, two and zero across the four records, so there is no column count that fits all of them. audit is a two-pocket list, so the record has depth as well as breadth. Reaching the shift means two hops, req[["audit"]][["shift"]], and each hop is an ordinary extraction rather than special nested-data machinery. The outer requests object is itself a list with no names at all, which is why the loop is for (req in requests) -- iterating over a list yields the pockets' contents in order, so req is already the inner record and no index arithmetic is needed.
Every extraction in the loop uses double brackets, deliberately. req[["pockets"]] cannot resolve to a pocket tab or a pockets_note tab by abbreviation the way req$pockets could. That does not make it safe -- a genuinely absent pockets tab still returns NULL rather than raising -- but it removes one whole class of wrong answer, and the class it removes is the one that returns plausible data belonging to a different field.
The counting is done with vectors rather than by incrementing. pockets %in% inventory returns one logical per requested pocket, sum of a logical vector counts the TRUE values, and missing is then pure subtraction, which is what makes the TOTAL line reconcile: seven asked, six found, one missing. The per-clerk tally goes through table, whose names come back in sorted order, so HALE, OKORO, VANCE appear in the same order on every run regardless of the order the dockets arrived in. Nothing here is printed from inside a conditional branch, so the report's shape does not depend on the data.
Now the flaw, and it is docket R-1044. That request asked for no pockets at all. character(0) has length zero, so asked is 0; character(0) %in% inventory returns logical(0), and sum(logical(0)) is 0, so found is 0; missing is therefore 0 and the status rule -- which only ever asks whether missing exceeded zero -- returns OK. The report states that three of four dockets were satisfied and lists no problem with R-1044, when in truth nobody retrieved anything for it. This is the zero-length trap in its purest form: over an empty vector every universal claim is vacuously true and every sum is zero, so an empty request passes precisely the checks that a fulfilled one does. A correct version needs a third status for asked == 0L and must exclude it from ok_count. Two further faults sit next to it. checked is printed in the CHK column and then never consulted, so R-1043's missing countersignature is visible to a human and invisible to the status rule -- had its pockets all been present it would have read OK while unverified. And %in% does not deduplicate, so a docket asking for c("A1", "A1") reports two asked and two found, booking one physical pocket as two successful retrievals and inflating the TOTAL line. A third, smaller: the clerk column is a hard %-7s, so a clerk named FITZGERALD widens that row alone and every column to its right stops lining up with the ruled lines above and below it.
Common Mistakes
- Using
[where[[was meant.model["coefficients"]returns a length-one list, not the numbers inside it, so the next line --mean(model["coefficients"])-- returnsNAwith a warning about the argument not being numeric or logical rather than an error you can trace. The tell is thatlength()on the result is 1 no matter how many values the pocket holds.
- Relying on
$partial matching.model$coefresolves tocoefficientstoday because that prefix is unique today. Add acoefficient_notespocket next quarter and the same expression returnsNULL; add acoefpocket and it silently starts returning something else entirely. None of the three behaviours produces a message.
- Treating a missing tab as an error condition that will announce itself.
x$typoandx[["typo"]]both returnNULLon a list.NULLthen flows into arithmetic as a zero-length vector, sosum(x$typo)is 0,length(x$typo)is 0, andif (x$typo > 5)throws about a zero-length condition several lines away from the actual typo.
- Assigning
NULLwhen you meant to storeNULL.x$k <- NULLdeletes the pocket and shortens the list. To keep the pocket and put an empty value in it you must writex["k"] <- list(NULL). Code that loops over a list clearing fields with<- NULLshrinks the list underneath itself, so any index computed before the loop is now wrong.
- Calling
unliston a mixed-type list. One character pocket coerces every number and every logical in the whole list to text, sounlist(list(a = 1L, b = "two", c = TRUE))gives"1" "two" "TRUE". Sorting or comparing that result uses string order, where"9"is greater than"60".
- Trusting
sapplyto return a vector.sapplysimplifies when it can and does not when it cannot, so the same function returns a numeric vector for one input, a matrix for another, and a list for a third -- and the difference only appears with real data. Usevapplywith an explicitFUN.VALUEso the shape is declared rather than inferred.
- Confusing element iteration with name iteration.
for (el in lst)bindselto each pocket's contents, not to its tab, solst[[el]]inside the loop is indexing by a value. When you need tabs, iterate overnames(lst); when you need positions, overseq_along(lst).
- Growing a list with
c()and losing the nesting.c(lst, new_record)splicesnew_record's pockets intolstas siblings whennew_recordis itself a list, so a four-record list gains four pockets instead of one. Appending one record requiresc(lst, list(new_record))orlst[[length(lst) + 1L]] <- new_record.
- Letting a zero-length component satisfy every check.
all(character(0) %in% inventory)isTRUE,sum(logical(0))is 0, andlength(character(0))is 0, so an empty pocket answers yes to every question a full one would. Any validation built out ofall,any, orsumneeds an explicitlength(x) > 0Lguard in front of it, or empty input reads as perfect input.
Best Practices
- Extract with
[[and subset with[, and keep$for interactive work at the console. The double bracket refuses abbreviations, which removes the failure mode hardest to notice in a report: a neighbouring field's contents returned under the name you asked for.
- Name every pocket at construction time, and never index a list by position in code that outlives the session. A positional index is a count from the left edge, and the day somebody inserts a field at the front every count in the file becomes silently wrong.
- Check for absence at the point of extraction, not downstream. A single
if (!("pockets" %in% names(req))) stop("record missing pockets")immediately after reading a record turns aNULLthat would have travelled twenty lines into an error naming the field and the record.
- Preallocate with
vector("list", n)and assign by index rather than appending withc()in a loop. Appending copies the whole list on every iteration, andc()splices list arguments instead of nesting them, so the wrong spelling grows the list by the wrong amount without complaint.
- Prefer
vapplyoversapplywhenever the result feeds anything else. DeclaringFUN.VALUE = numeric(1)makes a function that unexpectedly returns two values fail on the spot instead of quietly producing a matrix three steps later.
- Distinguish deleting from emptying in writing as well as in intent:
x[["k"]] <- NULLto remove the pocket,x["k"] <- list(NULL)to keep the pocket and empty it. Add a comment saying which you meant; the two lines look alike at a glance.
- Do not
unlistin order to compute or compare. Reach into the one pocket you actually need with[[, where the type is preserved, and treatunlistas a formatting step for lists of same-typed scalars only.
- Put a
length(x) > 0Lguard in front of everyall,any,min,max, andsumthat reads a variable-length component, and assert that your totals reconcile -- that asked equals found plus missing -- so an empty input shows up as a failed assertion rather than as a clean report.
Practice Exercises
- Fix the retrieval log so that docket R-1044 cannot pass. Add an
EMPTYstatus forasked == 0L, exclude it fromok_count, and add a line that stops the program unlesssum(asked_all)equalssum(found_all)plus the total missing. Then add a DUP column countingsum(duplicated(pockets))and confirm that a docket asking forc("A1", "A1")now reports one duplicate instead of two clean retrievals.
- Write
pluck(x, path, default = NA)that walks a nested list along a character vector of tab names -- sopluck(req, c("audit", "shift"))returns"EARLY"-- and returnsdefaultthe moment any level is absent rather than propagatingNULL. Test it on a path that exists, a path whose first hop is wrong, and a path whose last hop is wrong, printing all three results in one output block.
- Build a list with pockets named
total,totals, andconverged, then print a fixed-width table with one row per accessor form -- single bracket, double bracket, double bracket withexact = FALSE, and dollar -- and one column each for the name requested, the class of the result, and its length. Request both"totals"and the abbreviation"tot"and explain in a comment why exactly one row differs between the two requests.
- Build the same five-record list three ways: with
c()in a loop, withlst[[i]] <- record, and withvector("list", 5)filled by index. Printlengthandnamesfor each result and useidenticalto compare them pairwise. Explain in a comment why the naivec(lst, record)version has a different length from the other two, and what wrapping it inlist()changes.