Lists, Matrices, and Tables
Tables
Counting Categories
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 = "")
colors ← red, blue, red, green, red
1colors <- c("red", "blue", "red", "green", "red")2counts <- table(colors)values this stepred, blue, red, green, redcolorscounts ← 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, redcolorstop ← red
2counts <- table(colors)3top <- names(counts)[which.max(counts)]4cat(top, "\n", sep = "")values this stepredtopblue=1, green=1, red=3countscat(top, " ", sep = "")
3top <- names(counts)[which.max(counts)]4cat(top, "\n", sep = "")outputredvalues this stepredtop
Follow the Counts
colorsstarts as red, blue, red, green, red.table(colors)counts each color.- The counts are blue
1, green1, and red3. which.max(counts)picks the largest count.- 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.