Introduction to mappers

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

.f in purrr

A function:

  • for each elements of .x
  • do .f(.x, ...)

A number $n$:

  • for each elements of .x
  • do .x[$n$]

A character vector $z$

  • for each elements of .x
  • do .x[$z$]
Intermediate Functional Programming with purrr

.f as a function

When a function, .f can be either:

  • A classical function
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

 

  • A lambda (or anonymous) function
map_dbl(visit_2014, function(x) {
  round(mean(x))
})
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053
Intermediate Functional Programming with purrr

Mappers: part 1

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)))
Intermediate Functional Programming with purrr

Mappers: part 2

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)
Intermediate Functional Programming with purrr

as_mapper()

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))))
Intermediate Functional Programming with purrr

Why mappers?

Mappers are:

  • Concise

  • Easy to read

  • Reusable

Create mappers

Intermediate Functional Programming with purrr

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...