マッパーの概要

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

Colin Fay

Data Scientist & R Hacker at ThinkR

purrr における .f

関数の場合:

  • .x の各要素に対して
  • .f(.x, ...) を実行

整数 $n$ の場合:

  • .x の各要素に対して
  • .x[$n$] を実行

文字ベクトル $z$ の場合:

  • .x の各要素に対して
  • .x[$z$] を実行
purrr で学ぶ中級関数型プログラミング

関数としての .f

関数の場合、.f には次の形式が使えます:

  • 通常の関数
my_fun <- function(x) {
  round(mean(x))
}
map_dbl(visit_2014, my_fun)
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053

 

  • ラムダ(無名)関数
map_dbl(visit_2014, function(x) {
  round(mean(x))
})
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053
purrr で学ぶ中級関数型プログラミング

マッパー:パート1

マッパー:片側数式を用いた無名関数

# With one parameter 
map_dbl(visits2017, ~ round(mean(.x)))

# Is equivalent to 
map_dbl(visits2017, ~ round(mean(.)))

# Is equivalent to 
map_dbl(visits2017, ~ round(mean(..1)))
purrr で学ぶ中級関数型プログラミング

マッパー:パート2

マッパー:片側数式を用いた無名関数

# With two parameters
map2(visits2016, visits2017, ~ .x + .y)

# Is equivalent to 
map2(visits2016, visits2017, ~ ..1 + ..2)
# With more than two parameters
pmap(list, ~ ..1 + ..2 + ..3)
purrr で学ぶ中級関数型プログラミング

as_mapper()

as_mapper(): ラムダ関数からマッパーオブジェクトを作成

# Classical function 
round_mean <- function(x){
    round(mean(x))
}
# As a mapper
round_mean <- as_mapper(~ round(mean(.x))))
purrr で学ぶ中級関数型プログラミング

なぜマッパーを使うのか?

マッパーの特徴:

  • 簡潔

  • 読みやすい

  • 再利用可能

マッパーの作成

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

練習しましょう!

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

Preparing Video For Download...