substr("apple", start = 1, stop = 3)
[1] "app"
# Output: "app"
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.
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)
:
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 vectormap_lgl()
outputs a logical vectormap_chr()
outputs a character vector.f
.f
as a named function:map_chr(c("apple", "banana", "cherry"), substr, start = 1, stop = 3)
[1] "app" "ban" "che"
.f
as an anonymous function:map_chr(c("apple", "banana", "cherry"), function(x) substr(x, start = 1, stop = 3))
[1] "app" "ban" "che"
.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"
For each question, provide three solutions using a:
# 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(_______)
# 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(_______)
# 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()