lapply and sapply
Part of the Logic & Flow section of Coddy's R journey. Lesson 32 of 64.
lapply(x, f) calls f on every element of x and returns the results in a list, one element per input:
squares <- lapply(1:3, function(i) i^2)
print(length(squares))
print(squares[[3]])Output:
[1] 3
[1] 9sapply() does the same and simplifies the result: when every call returns one value, you get a plain vector instead of a list:
print(sapply(1:3, function(i) i^2))
print(sapply(c(4, 9, 16), sqrt))Output:
[1] 1 4 9
[1] 2 3 4Over a character vector, sapply() names the results after the inputs. Add USE.NAMES = FALSE for a plain vector:
words <- c("tea", "coffee")
print(sapply(words, nchar))
print(sapply(words, nchar, USE.NAMES = FALSE))Output:
tea coffee
3 6
[1] 3 6These functions replace the loop that builds a result one element at a time. Both versions below compute how many vowels each word has:
words <- c("banana", "sky", "idea")
vowels <- function(w) sum(strsplit(w, "")[[1]] %in% c("a", "e", "i", "o", "u"))
counts <- c()
for (w in words) counts <- c(counts, vowels(w))
print(counts)
print(sapply(words, vowels, USE.NAMES = FALSE))Output:
[1] 3 0 3
[1] 3 0 3Challenge
EasyComplete vowel_counts(words). Return one line per word, banana: 3, with the number of vowels (a, e, i, o, u) in the word. Use sapply() to count the vowels of all words.
The supplied code reads the words as a comma-separated line of lower-case words and prints each returned line.
Try it yourself
vowel_counts <- function(words) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(vowel_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