Grouped summaries in base R in R
Summarizing by group without any packages.
by_cyl <- aggregate(mpg ~ cyl, data = mtcars, FUN = mean)
two_way <- aggregate(mpg ~ cyl + am, data = mtcars, FUN = median)
counts <- table(mtcars$cyl)
cross <- table(mtcars$cyl, mtcars$am)
split_groups <- split(mtcars$mpg, mtcars$cyl)
group_sds <- sapply(split_groups, sd)
overall <- tapply(mtcars$mpg, mtcars$cyl, mean)
How it works
aggregateapplies a function per formula group.tablecounts categories, one-way or crossed.splitplussapply, ortapply, do the same job.
Keywords and builtins used here
aggregatesapplysplittabletapply
The run, in numbers
- Lines
- 9
- Characters to type
- 323
- Tokens
- 88
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 56 seconds.
Step 3 of 4 in Reshaping & combining, step 6 of 8 in Data frames in base R.