Functional Programming with purrr
Advanced
8 hrs
2 Concepts
Your Learning Map
📌 You already know
You can write your own functions in R.
🎯 You'll learn here
Replacing loops with purrr —
map, map_dbl, pmap, walk — for clean, vectorised pipelines.🌍 Where it's used
Running the same step over many files, models or API calls without copy-pasting loops.
🔗 Unlocks next
Powers reproducible pipelines in the capstone.
M1
map Functions
Concept 1
map, map_dbl, map_chr
purrr's map family replaces for loops with concise, readable code. Each variant enforces the output type.
R
library(purrr)
map(1:5, sqrt) # list
map_dbl(1:5, sqrt) # numeric vector
map_chr(c(1.1,2.2,3.3), as.character) # character vector
map_lgl(c(1,-1,2,-2), ~. > 0) # logical vector
# Two inputs:
map2_dbl(c(1,2,3), c(4,5,6), `+`) # 5 7 9
R — Apply a function to each value
LIVE READY
Output (verified)
[1] 1 4 9 16 25 36
Solved Examples
Example 1
Apply the concept of map, map_dbl, map_chr to a sample dataset. Show at least two approaches.
# See the code example above and adapt it to your data. # Always check your output with str() and head().
Self-Assessment (2 questions)
Q1. purrr::map() always returns:
map() returns a list; typed variants like map_dbl() return atomic vectors.
Q2. To get a numeric (double) vector instead of a list, you use:
map_dbl() returns a double vector; map_chr() returns a character vector.
M2
Advanced purrr
Concept 1
pmap and walk
pmap() applies a function to matching elements from multiple lists simultaneously. walk() is like map() but used for side effects.
R
# pmap: parallel map over multiple inputs
params <- list(mean=c(0,1,2), sd=c(1,2,3), n=rep(100,3))
pmap(params, rnorm) # 3 samples with different parameters
# walk: side effects (no return value)
list_of_dfs |> walk(~ write_csv(., paste0(deparse(substitute(.)),'.csv')))
Solved Examples
Example 1
Apply the concept of pmap and walk to a sample dataset. Show at least two approaches.
# See the code example above and adapt it to your data. # Always check your output with str() and head().
Self-Assessment (2 questions)
Q1. pmap() is used when you need to iterate over:
pmap() maps over multiple lists/columns in parallel, passing each set as arguments.
Q2. walk() differs from map() in that it:
walk() is for side effects (printing, saving) and returns its input invisibly.