Functional Programming with purrr
library(purrr)
map(1:3, \(x) x^2) # list
map_dbl(1:3, \(x) x^2) # double vector
map_chr(c("a", "b"), toupper)
map_lgl(list(1, "a"), is.numeric)
map_int(list(1:3, 1:5), length)
map(list(a = 1:3, b = 4:6), mean)
map(penguins, \(col) sum(is.na(col)))
map2_dbl(1:3, 4:6, \(x, y) x * y) # two inputs
pmap_dbl(list(a = 1:2, b = 3:4, c = 5:6), \(a, b, c) a + b + c)
imap_chr(c(x = 1, y = 2), \(val, name) paste(name, val))
walk(c("a", "b"), print) # side effects only
keep(1:10, \(x) x %% 2 == 0); discard(1:10, \(x) x > 5)
reduce(1:5, `+`); accumulate(1:5, `+`) # 15 / 1 3 6 10 15
compact(list(1, NULL, 2)); flatten(list(list(1), list(2))); list_rbind(list_of_dfs)
detect(1:10, \(x) x > 3); every(1:3, is.numeric); some(c(1, NA), is.na)
pluck(nested_list, "a", 1, "b") # safe deep extraction
modify_if(df, is.numeric, round)
# Error handling
safe_log <- safely(log); safe_log("a") # list(result = NULL, error = <error>)
possibly(log, otherwise = NA)("a") # NA
quietly(f); insistently(f, rate = rate_backoff()); slowly(f, rate_delay(1))
# Function operators
partial(round, digits = 2)(3.14159) # 3.14
compose(sqrt, abs)
…