使用 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
"映射器":用单边公式定义的匿名函数
# 一个参数
map_dbl(visits2017, ~ round(mean(.x)))
# 等价于
map_dbl(visits2017, ~ round(mean(.)))
# 等价于
map_dbl(visits2017, ~ round(mean(..1)))
"映射器":用单边公式定义的匿名函数
# 两个参数
map2(visits2016, visits2017, ~ .x + .y)
# 等价于
map2(visits2016, visits2017, ~ ..1 + ..2)
# 多于两个参数
pmap(list, ~ ..1 + ..2 + ..3)
as_mapper(): 基于 lambda 函数创建映射器对象
# 传统函数
round_mean <- function(x){
round(mean(x))
}
# 作为映射器
round_mean <- as_mapper(~ round(mean(.x))))
映射器具有:
简洁
易读
可复用

使用 purrr 的函数式编程进阶