Data Analysis
Aggregate
Grouped Totals
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 = "")
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 colssalessummary ← 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 colssaleseast_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$regioncat(east_total, " ", sep = "")
3east_total <- summary$amount[summary$region == "east"]4cat(east_total, "\n", sep = "")output15values this step15east_total
Follow the Groups
salesstarts with three rows: east10, west7, and east5.aggregate(amount ~ region, sales, sum)groups rows byregion.- The two east rows add to
15. - The west row stays
7. east_totalselects the east summary, so the script prints15. | 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.