aggregate computes summaries by group. Formula syntax names the value column and grouping column.

Program

Play the script to sum amounts by region and read the east total.

aggregate_summary.R
Replay: real traced execution (multi-file project)
sales <- data.frame(region = c("east", "west", "east"), amount = c(10, 7, 5))
summary <- aggregate(amount ~ region, sales, sum)
east_total <- summary$amount[summary$region == "east"]
cat(east_total, "\n", sep = "")
  1. sales ← 3 rows x 2 cols

    1sales <- data.frame(region = c("east", "west", "east"), amount = c(10, 7, 5))2summary <- aggregate(amount ~ region, sales, sum)
    values this step3 rows x 2 colssales
  2. summary ← 2 rows x 2 cols

    1sales <- data.frame(region = c("east", "west", "east"), amount = c(10, 7, 5))2summary <- aggregate(amount ~ region, sales, sum)3east_total <- summary$amount[summary$region == "east"]
    values this step2 rows x 2 colssummary3 rows x 2 colssales
  3. east_total ← 15

    2summary <- aggregate(amount ~ region, sales, sum)3east_total <- summary$amount[summary$region == "east"]4cat(east_total, "\n", sep = "")
    values this step15east_totaleast, westsummary$region
  4. cat(east_total, " ", sep = "")

    3east_total <- summary$amount[summary$region == "east"]4cat(east_total, "\n", sep = "")
    output15
    values this step15east_total

Follow the Groups

  1. sales starts with three rows: east 10, west 7, and east 5.
  2. aggregate(amount ~ region, sales, sum) groups rows by region.
  3. The two east rows add to 15.
  4. The west row stays 7.
  5. east_total selects the east summary, so the script prints 15. | region | source amounts | summary amount | | --- | --- | --- | | east | 10, 5 | 15 | | west | 7 | 7 |
aggregate `aggregate(amount ~ region, sales, sum)` groups by region and sums amounts.
formula `amount ~ region` reads as summarize amount by region.
grouped summary Grouped summaries reduce many rows to one row per group.

Exercise: aggregate_summary.R

Reproduce the output 15, then trace which two east rows add together to make the east summary.