← Back to R Course | Chapter 11: Apply Family | Lesson 4 of 6

tapply()

tapply splits numbers into groups by a label and calculates something for each group, like the average height for each class. It is a group-by-group calculator.

In this page:

  1. tapply()
Syntax
r
tapply(x, index, FUN)

tapply()

tapply(x, index, FUN) applies a function to subsets of a vector, grouped by a second vector (the index), similar in spirit to aggregate() but working directly on vectors rather than data frames.

It's a compact way to compute a per-group statistic without building a full data frame first. The result is an array indexed by the distinct group values.

Note: tapply() is the vector-based equivalent of aggregate() -- reach for it when you don't already have a data frame.

Example: tapply()

markup
scores <- c(90, 85, 70, 60, 95)
groups <- c("A", "A", "B", "B", "A")

averages <- tapply(scores, groups, mean)
print(averages)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Passing groups of a different length than the data, which gives an error.
  2. Expecting a data frame from tapply(), when it returns an array with names; use aggregate() for a data frame.
  3. Ignoring NA in the values, so a group's mean becomes NA unless na.rm = TRUE is passed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.