Functional Programming with purrr
map Functions
map, map_dbl, map_chr
purrr's map family replaces for loops with concise, readable code. Each variant enforces the output type.
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
# See the code example above and adapt it to your data. # Always check your output with str() and head().
Advanced purrr
pmap and walk
pmap() applies a function to matching elements from multiple lists simultaneously. walk() is like map() but used for side effects.
# 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')))
# See the code example above and adapt it to your data. # Always check your output with str() and head().