table counts how many times each category appears. Names on the result identify the categories.

Program

Play the script to count colors and pick the most frequent one.

tables.R
Replay: real traced execution (multi-file project)
colors <- c("red", "blue", "red", "green", "red")
counts <- table(colors)
top <- names(counts)[which.max(counts)]
cat(top, "\n", sep = "")
  1. colors ← red, blue, red, green, red

    1colors <- c("red", "blue", "red", "green", "red")2counts <- table(colors)
    values this stepred, blue, red, green, redcolors
  2. counts ← 3 rows x 2 cols

    1colors <- c("red", "blue", "red", "green", "red")2counts <- table(colors)3top <- names(counts)[which.max(counts)]
    values this step3 rows x 2 colscountsred, blue, red, green, redcolors
  3. top ← red

    2counts <- table(colors)3top <- names(counts)[which.max(counts)]4cat(top, "\n", sep = "")
    values this stepredtopblue=1, green=1, red=3counts
  4. cat(top, " ", sep = "")

    3top <- names(counts)[which.max(counts)]4cat(top, "\n", sep = "")
    outputred
    values this stepredtop

Follow the Counts

  1. colors starts as red, blue, red, green, red.
  2. table(colors) counts each color.
  3. The counts are blue 1, green 1, and red 3.
  4. which.max(counts) picks the largest count.
  5. The script prints red. | color | count | | --- | --- | | blue | 1 | | green | 1 | | red | 3 |
table `table(colors)` counts each distinct value.
names `names(counts)` exposes category labels.
which.max `which.max(counts)` finds the position of the largest count.

Exercise: tables.R

Reproduce the printed value red, then change one color in colors and predict which count changes before running it.