possibly()

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

About possibly()

`possibly() creates a function that returns either:

  • the result

  • the value of otherwise

library(purrr)
possible_sum <- possibly(sum, otherwise = "nop")
possible_sum(1)

possible_sum("a")
0

"nop"
Intermediate Functional Programming with purrr

Using possibly()

possibly() can return:

  • A logical
ps <- possibly(sum, FALSE)
ps("a")
FALSE
  • A NA
ps <- possibly(sum, NA)
ps("a")
NA

 

  • A character
ps <- possibly(sum, "nope")
ps("a")
"nope"
  • A number
ps <- possibly(sum, 0)
ps("a")
0
Intermediate Functional Programming with purrr

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...