Nástroje pro funkcionální programování v purrr

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

Funkce vyššího řádu

Funkce vyššího řádu může:

  • Přijímat jednu nebo více funkcí jako argumenty
  • Vracet funkci
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

Tři typy funkcí vyššího řádu

  • Funkcionály

  • Továrny funkcí

  • Operátory funkcí

Intermediate Functional Programming with purrr

Příslovce v purrr

Ošetření chyb a varování:

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

Použití `safely()` pro ošetření chyb

safely() vrací funkci, která vrátí:

  • $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

Extrakce prvků z výsledků `safely()`

map() & "result" nebo "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

Pojďme si procvičit!

Intermediate Functional Programming with purrr

Preparing Video For Download...