Functional Programming with purrr
R Programming & Data Analytics / Functional Programming with purrr

Functional Programming with purrr

Advanced 8 hrs 2 Concepts
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
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. What is the primary purpose of map, map_dbl, map_chr?
Q2. Which R package is most relevant for this topic?
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. What is the primary purpose of pmap and walk?
Q2. Which R package is most relevant for this topic?
Working with Databases in R Reproducible Research — R Markdown