Menu
Coddy logo textTech

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] 9

sapply() 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 4

Over 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 6

These 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 3
challenge icon

Challenge

Easy

Complete 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")
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