aggregate()
aggregate groups a table by a category and calculates a summary for each group, like finding the average score for each class. It saves you sorting and adding by hand.
In this page:
Syntax
aggregate(value ~ group, data = df, FUN = function_name)
aggregate()
aggregate(value ~ group, data = df, FUN = mean) groups a data frame by one column and computes a summary statistic (like mean or sum) per group, similar to SQL's GROUP BY.
This is the standard R base function for group-wise summarization before more specialized packages are introduced. The formula syntax, value ~ group, reads as "value, grouped by group".
Note:
The formula syntax value ~ group reads naturally as "summarize value, grouped by group".
Example: aggregate()
df <- data.frame(
team = c("A", "A", "B", "B"),
score = c(10, 20, 30, 40)
)
result <- aggregate(score ~ team, data = df, FUN = mean)
print(result)
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
- Writing the formula in the wrong direction such as
team ~ score, when the value goes on the left and the group on the right. - Forgetting
FUN = mean, or passingmean()with parentheses, which calls it immediately. - Having
NAin the values, so the mean isNAunless the rows are dropped orna.rm = TRUEis passed.
Chapter Summary
- Data is read from and written to files such as CSV files.
subset(),merge(), andorder()filter, combine, and sort data.table()andaggregate()summarize data.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: