使用 purrr 的 R 語言中級函式程式設計
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
mapper:使用單邊公式的匿名函式
# 一個參數
map_dbl(visits2017, ~ round(mean(.x)))
# 等同於
map_dbl(visits2017, ~ round(mean(.)))
# 等同於
map_dbl(visits2017, ~ round(mean(..1)))
mapper:使用單邊公式的匿名函式
# 兩個參數
map2(visits2016, visits2017, ~ .x + .y)
# 等同於
map2(visits2016, visits2017, ~ ..1 + ..2)
# 多於兩個參數
pmap(list, ~ ..1 + ..2 + ..3)
as_mapper():從 lambda 函式建立 mapper 物件
# 一般函式
round_mean <- function(x){
round(mean(x))
}
# 轉為 mapper
round_mean <- as_mapper(~ round(mean(.x))))
Mappers 的優點:
精簡
易讀
可重用

使用 purrr 的 R 語言中級函式程式設計