The many flavors of map()

Foundations of Functional Programming with purrr

Auriel Fournier

Instructor

Non-list outputs

# Map over survey_data and determine number of rows
map(survey_data, ~nrow(.x))
$`LakeErieS`
[1] 14

$`LakeErieN`
[1] 14

$`LakeErieW`
[1] 14

$`LakeErieE`
[1] 15
Foundations of Functional Programming with purrr

purrr::map_variants

List output

# Determine row number
map(survey_data, ~nrow(.x))

   

     

Double, a type of numeric

# Determine row number
map_dbl(survey_data, ~nrow(.x))
$`LakeErieS`
[1] 14

$`LakeErieN`
[1] 14

$`LakeErieW`
[1] 14

$`LakeErieE`
[1] 15
14 14 14 15
Foundations of Functional Programming with purrr

map_lgl()

List

# Determine row number
map(survey_data, ~nrow(.x))

 

 

Logical

# Determine if elements have 14 rows
map_lgl(survey_data, ~nrow(.x)==14)
$`LakeErieS`
[1] 14

$`LakeErieN`
[1] 14

$`LakeErieW`
[1] 14

$`LakeErieE`
[1] 15
TRUE TRUE TRUE FALSE
Foundations of Functional Programming with purrr

map_chr()

List output

# Map over species_names list
map(species_names, ~.x)

 

 

Character

# Map over species_names list
map_chr(species_names, ~.x)
$`LakeErieS`
[1] "Green Frog"

$`LakeErieN`
[1] "American Bullfrog"

$`LakeErieW`
[1] "Gray Treefrog"

$`LakeErieE`
[1] "Mudpuppy"
LakeErieS       LakeErieN 
"Green Frog"    "American Bullfrog" 
LakeErieW       LakeErieE 
"Gray Treefrog" "Mudpuppy"
Foundations of Functional Programming with purrr

Example time!

# Create a data frame called survey_rows
survey_rows <- data.frame(names = names(survey_data),
                       rows = NA)

# Map over survey_data to determine row number in each element survey_rows$rows <- map_dbl(survey_data, ~nrow(.x))
# Print out the survey_rows data frame survey_rows
    names       rows
1   LakeErieS   14
2   LakeErieN   14
3   LakeErieW   14
4   LakeErieE   15
Foundations of Functional Programming with purrr

Let's purrr-actice!

Foundations of Functional Programming with purrr

Preparing Video For Download...