2.5 map(.x, .f)

map(.x, .f) is a fundamental tidyverse function that applies function .f to each element of input vector .x and outputs a list. Let’s explore how it works through examples and practice.

Understanding map(.x, .f)

Consider this basic string manipulation that gets the first 3 characters of the character string:

substr("apple", start = 1, stop = 3)
[1] "app"
# Output: "app"

When working with vectors:

substr(c("apple", "banana", "cherry"), start = 1, stop = 3)
[1] "app" "ban" "che"
# Output: "app" "ban" "che"

Here’s how we achieve the same thing using map(.x, .f):

a) Fill in the blanks to complete this code chunk:

library(tidyverse)

# Fill in the arguments to map() to get the first 3 letters of each word
# map(
# .x = ___________, 
# .f = function(x) substr(x, start = ___, stop = ___)
# )

Notice that map() outputs a list. To get a character vector instead, use map_chr().

  • map_dbl() outputs a numeric vector
  • map_lgl() outputs a logical vector
  • map_chr() outputs a character vector

Three ways to write .f

  1. Write .f as a named function:
map_chr(c("apple", "banana", "cherry"), substr, start = 1, stop = 3)
[1] "app" "ban" "che"
  1. Write .f as an anonymous function:
map_chr(c("apple", "banana", "cherry"), function(x) substr(x, start = 1, stop = 3))
[1] "app" "ban" "che"
  1. Write .f as a formula, using ~ and referring to .x directly:
map_chr(c("apple", "banana", "cherry"), ~ substr(.x, start = 1, stop = 3))
[1] "app" "ban" "che"

Practice Questions

For each question, provide three solutions using a:

  • Named function
  • Anonymous function
  • Formula syntax

b) Round these numbers to the nearest whole number:

# Using round() as a vectorized function: 
round(c(1.234, 2.345, 3.456))
[1] 1 2 3
# Using map() to vectorize round():
# a) Named function:
# map_dbl(_______)

# b) Anonymous function:
# map_dbl(_______)

# c) Formula:
# map_dbl(_______)

c) Round these numbers to 2 decimal places:

# Using round() as a vectorized functtion: 
round(c(1.234, 2.345, 3.456), digits = 2)
[1] 1.23 2.35 3.46
# Using map() to vectorize round():
# a) Named function:
# map_dbl(_______)

# b) Anonymous function:
# map_dbl(_______)

# c) Formula:
# map_dbl(_______)

d) Split these strings at the hyphen:

# Original vector: c("a-b", "c-d", "e-f")
# Desired output: A list where each element is a character vector of length 2
# Complete all three approaches using strsplit()