R / CHAPTER 08
Lists and predictable transformations
AdvancedTransform heterogeneous structures without surprising output shapes.
By the end of this chapter
- Distinguish [ from [[ on lists
- Use lapply for list-preserving results
- Use vapply with an explicit result template
The idea
A list can hold elements of different types and lengths, including other lists, vectors, and data frames. Single brackets return a sublist, preserving the outer container. Double brackets extract one element itself. This distinction matters when a function expects a numeric vector rather than a list containing that vector. Named list elements provide readable access when position alone is not meaningful.
lapply applies a function to each element and always returns a list. vapply additionally requires a result template, making the expected type and length explicit and checking each result against it. sapply tries to simplify automatically, which can be convenient interactively but creates less predictable shapes for reusable code. Select the transformation tool from the output contract, not merely from which function name is shortest.
groups <- list(red = c(2, 5), blue = c(4, 6, 8))
totals <- vapply(groups, sum, numeric(1))
cat(totals["red"], "
", sep = "")
cat(totals["blue"], "
", sep = "")7 18
Each sum produces one numeric result matching the template. vapply combines these results into a named numeric vector while retaining the group names.
Try it yourself
Use vapply to return a named logical vector saying which list elements have at least three entries.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING