Intermediate Functional Programming with purrr
Colin Fay
Data Scientist & R Hacker at ThinkR
A function:
A number $n$:
A character vector $z$
When a function, .f
can be either:
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: anonymous function with a one-sided formula
# 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)))
mapper: anonymous function with a one-sided formula
# 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()
: create mapper objects from a lambda function
# Classical function
round_mean <- function(x){
round(mean(x))
}
# As a mapper
round_mean <- as_mapper(~ round(mean(.x))))
Mappers are:
Concise
Easy to read
Reusable
Intermediate Functional Programming with purrr