Tools for functional programming in purrr

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

High order functions

A high order function can:

  • Take one or more functions as arguments
  • Return a function
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
Intermediate Functional Programming with purrr

Three types of high order functions

  • Functionals

  • Function factories

  • Function operators

Intermediate Functional Programming with purrr

Adverbs in purrr

Handling errors and warnings:

  • possibly()
  • safely()
library(purrr)
safe_mean <- safely(mean)
class(safe_mean)
"function"
Intermediate Functional Programming with purrr

Use safely() to handle error.

safely() returns a function that will return:

  • $result
  • $error
safe_log <- safely(log)
safe_log("a")
$result
NULL
$error
<simpleError in log(x = x, base = base): non-numeric argument to mathematical function>
Intermediate Functional Programming with purrr
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>
Intermediate Functional Programming with purrr

Extracting elements from `safely()` results

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

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...