typestar

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

  1. aggregate applies a function per formula group.
  2. table counts categories, one-way or crossed.
  3. split plus sapply, or tapply, do the same job.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Reshaping & combining, step 6 of 8 in Data frames in base R.

← Previous Next →