Looping Over Names
Part of the Logic & Flow section of Coddy's R journey. Lesson 10 of 64.
A for loop over names(x) visits every key, and x[[key]] gives the value for that key:
scores <- c(ada = 91, bo = 78, cy = 85)
for (name in names(scores)) {
cat(name, "scored", scores[[name]], "\n")
}Output:
ada scored 91
bo scored 78
cy scored 85 Entries keep the order they were added in. Loop over sort(names(x)) for alphabetical order:
scores <- c(cy = 85, ada = 91, bo = 78)
for (name in sort(names(scores))) {
cat(name, scores[[name]], "\n")
}Output:
ada 91
bo 78
cy 85 Looping over the input and updating a lookup table counts how often each value appears. The first time a word is seen it gets 1, after that it goes up by 1:
words <- c("red", "blue", "red", "green", "red")
counts <- c()
for (w in words) {
if (w %in% names(counts)) {
counts[w] <- counts[w] + 1
} else {
counts[w] <- 1
}
}
print(counts[["red"]])
print(names(counts))Output:
[1] 3
[1] "red" "blue" "green"To build output lines, collect them in a vector inside the loop and return or print them at the end:
scores <- c(ada = 91, bo = 78)
lines <- c()
for (name in names(scores)) {
lines <- c(lines, paste0(name, ": ", scores[[name]]))
}
cat(lines, sep = "\n")Output:
ada: 91
bo: 78Challenge
EasyComplete word_counts(words). Return one line per distinct word, in alphabetical order, formatted as word: count.
The supplied code reads the words as one line separated by spaces and prints each returned line.
Try it yourself
word_counts <- function(words) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(word_counts(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