Intermediate Functional Programming with purrr
Colin Fay
Data Scientist & R Hacker at ThinkR
A high order function can:
nop_na <- function(fun){ function(...){ fun(..., na.rm = TRUE) } }sd_no_na <- nop_na(sd) sd_no_na( c(NA, 1, 2, NA) )
0.7071068
Functionals
Function factories
Function operators
Handling errors and warnings:
possibly()safely()library(purrr)
safe_mean <- safely(mean)
class(safe_mean)
"function"
safely() returns a function that will return:
$result $errorsafe_log <- safely(log)
safe_log("a")
$result
NULL
$error
<simpleError in log(x = x, base = base): non-numeric argument to mathematical function>
map( list(2, "a"), log )
Error in log(x = x, base = base) : non-numeric argument to mathematical function
map( list(2, "a"), safely(log) )
[[1]]
[[1]]$result
[1] 0.6931472
[[1]]$error
NULL
[[2]]
[[2]]$result
NULL
[[2]]$error
<simpleError in log(x = x, base = base):non-numeric argument to mathematical function>
map() & "result" or "error"
safe_log <- safely(log)
map( list("a", 2), safe_log) %>%
map("result")
[[1]]
NULL
[[2]]
[1] 0.6931472
safe_log <- safely(log)
map( list("a", 2), safe_log ) %>%
map("error")
[[1]]
<simpleError in log(x = x,
base = base): non-numeric argument
to mathematical function>
[[2]]
NULL
Intermediate Functional Programming with purrr