purrr の関数型プログラミングツール

purrr で学ぶ中級関数型プログラミング

Colin Fay

Data Scientist & R Hacker at ThinkR

高階関数

高階関数でできること:

  • 1つ以上の関数を引数として受け取る
  • 関数を返す
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
purrr で学ぶ中級関数型プログラミング

高階関数の3種類

  • 汎関数

  • 関数ファクトリ

  • 関数演算子

purrr で学ぶ中級関数型プログラミング

purrr のアドバーブ

エラーと警告の処理:

  • possibly()
  • safely()
library(purrr)
safe_mean <- safely(mean)
class(safe_mean)
"function"
purrr で学ぶ中級関数型プログラミング

`safely()` によるエラー処理

safely() は以下を返す関数を返します:

  • $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>
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>
purrr で学ぶ中級関数型プログラミング

`safely()` の結果から要素を抽出する

map()"result" または "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
purrr で学ぶ中級関数型プログラミング

練習しましょう!

purrr で学ぶ中級関数型プログラミング

Preparing Video For Download...