Lesson contents

R — Counting factor levels with table

In R, table counts observations at each factor level. Declaring the levels in advance keeps a category in the result even when its count is zero.

A simple example

Look up one count

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
Lesson.R
counts <- c(A = 2)
cat(counts[["A"]])
Output
2
Advertisements

Count labels without relying on storage order

The factor declares the possible categories and their order. table counts observations at each level. A declared but unobserved level is retained with a count of zero.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.

Run the example

R 4. Run these commands from the directory containing the example.

Rscript Lesson.R
Lesson.R
colors <- factor(c("red", "blue", "red"), levels = c("red", "blue"))
counts <- table(colors)
for (color in names(counts)) {
  cat(sprintf("%s %d\n", color, counts[[color]]))
}
Output
red 2
blue 1

The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.

Try it yourself

Insert another blue before the last red. What changes?

Check your answer

Both keys now have a count of two. The requested display order stays red, then blue.

An Introduction to R

Related tags

  • R
  • collections
  • frequency counts
  • lookup