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 3sort(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] 2A 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] 3Challenge
EasyComplete 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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler