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:
Syntax
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()
scores <- c(90, 85, 70, 60, 95)
groups <- c("A", "A", "B", "B", "A")
averages <- tapply(scores, groups, mean)
print(averages)
Login to try C/C++/Java/PHP code in the editor
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
- Passing groups of a different length than the data, which gives an error.
- Expecting a data frame from
tapply(), when it returns an array with names; useaggregate()for a data frame. - Ignoring
NAin the values, so a group's mean becomesNAunlessna.rm = TRUEis passed.