Library contents

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

  1. Start with A has 1, A has 2, B has 4
  2. Do this Sum values for each key
  3. Result A = 3, B = 4
The A values combine into one subtotal. B contributes to its own group.

Syntax

R 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.

First output lineeast=4
Lesson.R
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 = "")
Output
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.

R documentation for tapply

Advertisements

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?

GivenArt 4 · Lab 8 · Art 3 | Art total
Worked result7

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?

GivenW 6 · E 9 · W 4 | W total
Worked result10