← Back to R Course | Chapter 8: Data Manipulation | Lesson 7 of 7

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:

  1. aggregate()
Syntax
r
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()

markup
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)
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. Writing the formula in the wrong direction such as team ~ score, when the value goes on the left and the group on the right.
  2. Forgetting FUN = mean, or passing mean() with parentheses, which calls it immediately.
  3. Having NA in the values, so the mean is NA unless the rows are dropped or na.rm = TRUE is passed.
Chapter Summary
  • Data is read from and written to files such as CSV files.
  • subset(), merge(), and order() filter, combine, and sort data.
  • table() and aggregate() summarize data.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.