Menu
Coddy logo textTech

Counting with table()

Part of the Logic & Flow section of Coddy's R journey. Lesson 15 of 64.

table(x) counts how many times each value occurs. The result is named by the values, sorted alphabetically, so the count of a value is t[["value"]]:

votes <- c("tea", "coffee", "tea", "juice", "tea")
t <- table(votes)
print(t[["tea"]])
print(names(t))
print(as.vector(t))

Output:

[1] 3
[1] "coffee" "juice"  "tea"   
[1] 1 1 3

sort(t, decreasing = TRUE) orders the counts from highest to lowest. which.max(t) gives the position of the largest count; when counts tie, it picks the first, which is the alphabetically first value:

votes <- c("tea", "coffee", "tea", "juice", "coffee")
t <- table(votes)
print(names(t)[which.max(t)])
print(max(t))

Output:

[1] "coffee"
[1] 2

A value that never occurs is not in the table at all, so check with %in% names(t) before reading it:

t <- table(c("A", "B", "A"))
for (grade in c("A", "B", "C")) {
  n <- if (grade %in% names(t)) t[[grade]] else 0
  cat(grade, n, "\n")
}

Output:

A 2 
B 1 
C 0 

table() counts numbers and logical values too. To count a single value, sum(x == value) is shorter than building a table:

rolls <- c(6, 2, 6, 6, 1)
print(sum(rolls == 6))
print(table(rolls > 3)[["TRUE"]])

Output:

[1] 3
[1] 3
challenge icon

Challenge

Easy

Complete vote_winner(votes). Return the option with the most votes followed by its count, as in tea (3 votes). When options tie, return the one that comes first alphabetically.

The supplied code reads the votes as a comma-separated line and prints the returned value.

Try it yourself

vote_winner <- function(votes) {
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(vote_winner(strsplit(input[1], ",")[[1]]), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler