Chapter 2 purrr basics
2.1 map function
2.1.1 I want to…
Start using {purrr}.
2.1.2 Here’s how to:
The base skeleton of {purrr} iteration functions are:
2.1.3 Ok, but why?
In this skeleton:
.x
is a list, a data.frame or a vector..f
is the function, formula or atomic vector that will be applied on each element of.f
.
Here, what map
does is applying the function to each element of a list. The returned object is always a list.
2.2 map_* functions
2.2.1 I want to…
Control the output of my iterations.
2.2.2 Here’s how to:
## [1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751
## [8] 2.828427 3.000000 3.162278
2.2.3 Ok, but why?
You can control the output of your map with these functions: map_lgl
map_chr
map_int
map_dbl
map_dfr
map_dfc
.
2.3 Mappers
2.3.1 I want to…
Create a function on the fly.
2.3.3 Ok, but why?
One sided formulaes, also called mappers, can be created as the .f
argument of map. It is build with ~
, then .x
refers to the element of the list in .x
.
When mapping on two elements, you can use .x
and .y
. With more than two elements, refer to them with ..1
, ..2
, ..3
, etc.
2.4 map on 2 elements
2.4.1 I want to…
map over two lists.
2.4.2 Here’s how to:
## [1] "a A" "b B" "c C" "d D" "e E" "f F" "g G" "h H" "i I" "j J" "k K"
## [12] "l L" "m M" "n N" "o O" "p P" "q Q" "r R" "s S" "t T" "u U" "v V"
## [23] "w W" "x X" "y Y" "z Z"
2.4.3 Ok, but why?
map2
and friends (map2
map2_lgl
map2_int
map2_dbl
map2_chr
map2_dfr
map2_dfc
) allows to map over two elements.
2.5 map on more elements
2.5.1 I want to…
map over more than two lists.
2.5.2 Here’s how to:
## [1] 6 9 12
2.5.3 Ok, but why?
pmap
and friends (pmap_lgl
pmap_int
pmap_dbl
pmap_chr
pmap_dfr
pmap_dfc
) allows to map over more than two elements.
2.6 Iteration for side effect
2.6.1 I want to…
Iterate only for side effect.
2.6.2 Here’s how to:
2.6.3 Ok, but why?
walk
is the silent conterpart of map, but invisible: you call it just for side effects. map_*
, map2_*
, pwalk
and friends also exists.