Úvod do mapperů

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

.f v purrr

Funkce:

  • pro každý prvek .x
  • provede .f(.x, ...)

Číslo $n$:

  • pro každý prvek .x
  • provede .x[$n$]

Znakový vektor $z$

  • pro každý prvek .x
  • provede .x[$z$]
Intermediate Functional Programming with purrr

.f jako funkce

Pokud je .f funkcí, může být:

  • Klasická funkce
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

 

  • Lambda (anonymní) funkce
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

Mappery: část 1

mapper: anonymní funkce s jednostrannou formulí

# S jedním parametrem 
map_dbl(visits2017, ~ round(mean(.x)))

# Je ekvivalentní s 
map_dbl(visits2017, ~ round(mean(.)))

# Je ekvivalentní s 
map_dbl(visits2017, ~ round(mean(..1)))
Intermediate Functional Programming with purrr

Mappery: část 2

mapper: anonymní funkce s jednostrannou formulí

# Se dvěma parametry
map2(visits2016, visits2017, ~ .x + .y)

# Je ekvivalentní s 
map2(visits2016, visits2017, ~ ..1 + ..2)
# S více než dvěma parametry
pmap(list, ~ ..1 + ..2 + ..3)
Intermediate Functional Programming with purrr

as_mapper()

as_mapper(): vytvoření mapper objektů z lambda funkce

# Klasická funkce 
round_mean <- function(x){
    round(mean(x))
}
# Jako mapper
round_mean <- as_mapper(~ round(mean(.x))))
Intermediate Functional Programming with purrr

Proč mappery?

Mappery jsou:

  • Stručné

  • Přehledné

  • Znovupoužitelné

Vytváření mapperů

Intermediate Functional Programming with purrr

Pojďme si to procvičit!

Intermediate Functional Programming with purrr

Preparing Video For Download...