R tapply
tapply splits a vector by factor levels, applies a function to each group, and arranges the answers by level.
A simple example
tapply
- Start with A has 1, A has 2, B has 4
- Do this Sum values for each key
- Result A = 3, B = 4
Syntax
tapply(values, groups, sum, na.rm = TRUE)
Run this example in R
Save the program as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.R
Compute a total for each region
A team receives a batch of readings or transactions and wants a compact report. Aggregate the records by the requested grouping so the result can be checked against the individual inputs.
region <- factor(c("east", "west", "east"), levels = c("east", "west", "north"))
totals <- tapply(c(4, 0, NA_real_), region, sum, na.rm = TRUE)
for (name in names(totals)) cat(name, "=", totals[[name]], "\n", sep = "")
east=4 west=0 north=NA
An unused factor level has no group and receives the default empty-cell value NA. A group with an observed zero still has a numerical total.
Total studio deliveries
A store records three boxes of supplies against their destination studios. Group the quantities by location and add the values within each group. What total belongs to the named location?
Total tickets by door
The front desk receives two west-door reports and an east-door report. Group the quantities by location and add the values within each group. What total belongs to the named location?