purrr で学ぶ中級関数型プログラミング
Colin Fay
Data Scientist & R Hacker at ThinkR
関数の場合:
整数 $n$ の場合:
文字ベクトル $z$ の場合:
関数の場合、.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
マッパー:片側数式を用いた無名関数
# 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)))
マッパー:片側数式を用いた無名関数
# 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)
as_mapper(): ラムダ関数からマッパーオブジェクトを作成
# Classical function
round_mean <- function(x){
round(mean(x))
}
# As a mapper
round_mean <- as_mapper(~ round(mean(.x))))
マッパーの特徴:
簡潔
読みやすい
再利用可能

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