R / CHAPTER 10

Grouped summaries and validation

Advanced

Summarize groups with explicit missing-data and input rules.

By the end of this chapter

  • Split data into named groups
  • State summary policies for missing data
  • Reject unsupported input before calculating

The idea

A grouped calculation separates observations by a key, applies the same operation to each group, and combines the results. In base R, split creates a list of groups that can be processed with lapply or vapply. Keep the group labels attached to the results so callers can identify each summary without guessing an order. Validate that the grouping key has the intended relationship to the observations.

Missingness changes the meaning of a summary. An all-missing group should not silently become evidence that a real measurement equals zero unless that is the stated requirement. A small helper can distinguish that case before using na.rm = TRUE. stop raises an error for unsupported input, while tryCatch can handle a failure at a boundary where the program knows what useful action to take.

R example
known_mean <- function(x) {
  if (all(is.na(x))) return(NA_real_)
  mean(x, na.rm = TRUE)
}
values <- c(2, 6, NA, 10)
team <- c("A", "A", "B", "B")
means <- vapply(split(values, team), known_mean, numeric(1))
cat(means["A"], ":", means["B"], "
", sep = "")
Result
4:10

Group A averages two known observations. Group B averages its one known observation, while the helper would return NA for an entirely missing group.

Try it yourself

Return a named count of known observations per group, and reject inputs whose lengths differ.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What should known_mean(c(NA_real_, NA_real_)) return under the displayed helper’s contract?