๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R tapply

tapply() runs a function on groups of values. The groups come from a factor.

Grouped means in level order

The data starts with group b. The result starts with group a, since the levels run in alphabetical order.

vals <- c(10, 20, 30, 40)
grp <- factor(c("b", "a", "b", "a"))
print(tapply(vals, grp, mean))

Grouped sums

sum replaces mean in the same shape of call. Each group now prints its total.

vals <- c(10, 20, 30, 40)
grp <- factor(c("b", "a", "b", "a"))
print(tapply(vals, grp, sum))

Two areas side by side

The sales values split into east and west groups. The result prints the east total first, in level order.

sales <- c(100, 150, 200, 250)
area <- factor(c("west", "east", "west", "east"))
print(tapply(sales, area, sum))

A written function per group

The function gives the gap between the largest and smallest value. Each group has a gap of 20.

vals <- c(10, 20, 30, 40)
grp <- factor(c("b", "a", "b", "a"))
print(tapply(vals, grp, function(v) max(v) - min(v)))

Example

scores <- c(80, 90, 70, 100)
group <- factor(c("junior", "senior", "junior", "senior"))
print(tapply(scores, group, mean))
print(tapply(scores, group, sum))

Key points

  • tapply() takes the values first and the grouping factor second.
  • The third value is the function to run on each group.
  • The result holds one value for each group.
  • The groups appear in factor level order.
  • A factor holds the levels that define the groups.

In this example the scores split into junior and senior groups. The first tapply call prints the mean of each group and the second prints the sum of each group.

Note

The print shape is a one-row array with the group names as its headers.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

In what order do the groups appear in a tapply() result?