Front
Back
How do you iterate with purrr::map() variants?
map() returns list; map_dbl/map_int/map_chr enforce types.
Code:
library(purrr)
map_dbl(1:5, ~ .x^2)
map2_chr(letters[1:3], 1:3, ~ paste0(.x, .y))
pmap_dbl(list(a=1:3, b=4:6), ~ ..1 + ..2)
How do you handle missing or failing iterations in purrr?
Use possibly() and safely() wrappers.
Code:
library(purrr)
safe_log <- safely(log, otherwise = NA_real_)
map_dbl(c(1, -1, 10), ~ safe_log(.x)$result)
How do you reduce/accumulate values with purrr?
Use reduce() and accumulate().
Code:
library(purrr)
reduce(1:5, +) # 15
accumulate(1:5, +) # 1 3 6 10 15