Sei sulla pagina 1di 2

Apply functions with purrr : : CHEAT SHEET

Apply Functions Work with Lists


Map functions apply a function iteratively to each element of a list FILTER LISTS SUMMARISE LISTS TRANSFORM LISTS
or vector.
map(.x, .f, …) Apply a a b pluck(.x, ..., .default=NULL) a FALSE every(.x, .p, …) Do all a a modify(.x, .f, ...) Apply
fun( ,…) b Select an element by name elements pass a test? function to each element. Also
map( , fun, …) fun( ,…) function to each b b b
element of a list or c or index, pluck(x,"b") ,or its c every(x, is.character) c c map, map_chr, map_dbl,
fun( ,…) d attribute with attr_getter. d d map_dfc, map_dfr, map_int,
vector. map(x, is.logical)
pluck(x,"b",attr_getter("n")) a TRUE some(.x, .p, …) Do some map_lgl. modify(x, ~.+ 2)
b elements pass a test? 

map2(.x, ,y, .f, …) Apply a a keep(.x, .p, …) Select c some(x, is.character) a a modify_at(.x, .at, .f, ...) Apply
fun( , ,…) elements that pass a function to elements by name
map2( , ,fun,…) fun( , ,…) a function to pairs of b c b b
fun( , ,…) elements from two lists, c logical test. keep(x, is.na) a TRUE has_element(.x, .y) Does a c c or index. Also map_at.
vectors. map2(x, y, sum) b list contain an element? d d modify_at(x, "b", ~.+ 2)
a b discard(.x, .p, …) Select c has_element(x, "foo")
b elements that do not pass a a a modify_if(.x, .p, .f, ...) Apply
pmap(.l, .f, …) Apply a c logical test. discard(x, is.na) detect(.x, .f, ..., .right=FALSE, b b function to elements that
fun( , , ,…) function to groups of a c
pmap( ,fun,…) fun( , , ,…) b .p) Find first element to pass. c c pass a test. Also map_if.
fun( , , ,…) elements from list of lists, a NULL b compact(.x, .p = identity)
 c detect(x, is.character) d d modify_if(x, is.numeric,~.+2)
vectors. pmap(list(x, y, z), b Drop empty elements.
sum, na.rm = TRUE) c NULL compact(x) detect_index(.x, .f, ..., .right modify_depth(.x,.depth,.f,...)
a 3
b = FALSE, .p) Find index of Apply function to each
a a head_while(.x, .p, …) c first element to pass. element at a given level of a
fun invoke_map(.f, .x = detect_index(x, is.character) list. modify_depth(x, 1, ~.+ 2)
fun ( ,…)
list(NULL), …, .env=NULL) b b Return head elements
invoke_map( fun , ,…) fun ( ,…) c until one does not pass.
Run each function in a list. xy z 2
fun fun ( ,…) d Also tail_while. a vec_depth(x) Return depth
Also invoke. l <- list(var, head_while(x, is.character) b (number of levels of WORK WITH LISTS
sd); invoke_map(l, x = 1:9) c indexes). vec_depth(x) array_tree(array, margin =
lmap(.x, .f, ...) Apply function to each list-element of a list or vector. NULL) Turn array into list.
RESHAPE LISTS JOIN (TO) LISTS Also array_branch.
imap(.x, .f, ...) Apply .f to each element of a list or vector and its index.
array_tree(x, margin = 3)
a flatten(.x) Remove a level + append(x, values, after =
OUTPUT of indexes from a list. Also length(x)) Add to end of list. cross2(.x, .y, .filter = NULL)
b +
map(), map2(), pmap(), function returns c flatten_chr, flatten_dbl, append(x, list(d = 1)) All combinations of .x
imap and invoke_map flatten_dfc, flatten_dfr, and .y. Also cross, cross3,
map list flatten_int, flatten_lgl. prepend(x, values, before = cross_df. cross2(1:3, 4:6)
each return a list. Use a +
suffixed version to map_chr character vector flatten(x) 1) Add to start of list.
return the results as a map_dbl double (numeric) vector prepend(x, list(d = 1)) a p set_names(x, nm = x) Set
specific type of flat xy x y transpose(.l, .names = b q the names of a vector/list
vector, e.g. map2_chr, map_dfc data frame (column bind) a a NULL) Transposes the index + splice(…) Combine objects c r directly or with a function.
pmap_lgl, etc. map_dfr data frame (row bind) b b order in a multi-level list. into a list, storing S3 objects set_names(x, c("p", "q", "r"))
c c transpose(x) + as sub-lists. splice(x, y, "foo") set_names(x, tolower)
Use walk, walk2, and map_int integer vector
pwalk to trigger side map_lgl logical vector
effects. Each return its
input invisibly.
walk triggers side effects, returns
the input invisibly
Reduce Lists Modify function behavior
a b
func + a b c d func( , ) reduce(.x, .f, ..., .init, .dir = compose() Compose negate() Negate a quietly() Modify
SHORTCUTS - within a purrr function: c("forward", "backward")) multiple functions. predicate function (a function to return
c
"name" becomes ~ .x .y becomes func( , ) Apply function recursively pipe friendly !) list of results,
function(x) x[["name"]], function(.x, .y) .x .y, e.g.
d to each element of a list or lift() Change the type output, messages,
func( , ) vector. Also reduce2. of input a function partial() Create a warnings.
e.g. map(l, "a") extracts a map2(l, p, ~ .x +.y ) becomes
from each element of l map2(l, p, function(l, p) l + p ) reduce(x, sum) takes. Also lift_dl, version of a function
lift_dv, lift_ld, lift_lv, that has some args possibly() Modify
~ .x becomes function(x) x, ~ ..1 ..2 etc becomes a b c d func( , ) lift_vd, lift_vl. preset to values. function to return
func + accumulate(.x, .f, ..., .init)
e.g. map(l, ~ 2 +.x) becomes function(..1, ..2, etc) ..1 ..2 etc, c Reduce, but also return default value
func( , ) rerun() Rerun safely() Modify func whenever an error
map(l, function(x) 2 + x ) e.g. pmap(list(a, b, c), ~ ..3 + ..1 - ..2) d intermediate results. Also
becomes pmap(list(a, b, c), func( , ) expression n times. to return list of occurs (instead of
accumulate2. results and errors. error).
function(a, b, c) c + a - b) accumulate(x, sum)

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at purrr.tidyverse.org • purrr 0.2.3 • Updated: 2019-08
Nested Data "cell" contents
List Column Workflow Nested data frames use a list column, a list that is stored as a
column vector of a data frame. A typical workflow for list columns:
A nested data frame stores

1 2 3
Sepal.L Sepal.W Petal.L Petal.W
individual tables within the 5.1 3.5 1.4 0.2 Make a list Work with Simplify
cells of a larger, organizing 4.9 3.0 1.4 0.2 column list columns the list
4.7 3.2 1.3 0.2
column
S.L S.W P.L P.W
table. 4.6 3.1 1.5 0.2 Species S.L S.W P.L P.W 5.1 3.5 1.4 0.2
Call:
lm(S.L ~ ., df)
setosa 5.1 3.5 1.4 0.2 4.9 3.0 1.4 0.2
5.0 3.6 1.4 0.2 Coefs:
setosa 4.9 3.0 1.4 0.2 4.7 3.2 1.3 0.2
(Int) S.W P.L P.W
n_iris$data[[1]] setosa 4.7 3.2 1.3 0.2 4.6 3.1 1.5 0.2 2.3 0.6 0.2 0.2
setosa 4.6 3.1 1.5 0.2
nested data frame Sepal.L Sepal.W Petal.L Petal.W versi 7.0 3.2 4.7 1.4
Species data S.L S.W P.L P.W
7.0 3.2 4.7 1.4
Species data model Call: Species beta
setos <tibble [50x4]> lm(S.L ~ ., df)
versi 6.4 3.2 4.5 1.5 setosa <tibble [50x4]> <S3: lm> setos 2.35
Species data 7.0 3.2 4.7 1.4 versi <tibble [50x4]> 6.4 3.2 4.5 1.5
versi 6.9 3.1 4.9 1.5 versi <tibble [50x4]> <S3: lm> Coefs: versi 1.89
virgini <tibble [50x4]> 6.9 3.1 4.9 1.5
setosa <tibble [50 x 4]> 6.4 3.2 4.5 1.5 versi 5.5 2.3 4.0 1.3 virgini <tibble [50x4]> <S3: lm> (Int) S.W P.L P.W virgini 0.69
5.5 2.3 4.0 1.3 1.8 0.3 0.9 -0.6
versicolor <tibble [50 x 4]> 6.9 3.1 4.9 1.5 virgini 6.3 3.3 6.0 2.5
virginica <tibble [50 x 4]> 5.5 2.3 4.0 1.3 virgini 5.8 2.7 5.1 1.9 S.L S.W P.L P.W
virgini 7.1 3.0 5.9 2.1 Call:
n_iris 6.5 2.8 4.6 1.5 6.3 3.3 6.0 2.5
lm(S.L ~ ., df)
virgini 6.3 2.9 5.6 1.8 5.8 2.7 5.1 1.9
n_iris$data[[2]] 7.1 3.0 5.9 2.1 Coefs:
(Int) S.W P.L P.W
6.3 2.9 5.6 1.8 0.6 0.3 0.9 -0.1

Sepal.L Sepal.W Petal.L Petal.W n_iris <- iris %>% mod_fun <- function(df) b_fun <- function(mod)
Use a nested data frame to: 6.3 3.3 6.0 2.5 group_by(Species) %>% lm(Sepal.Length ~ ., data = df) coefficients(mod)[[1]]
5.8 2.7 5.1 1.9 nest()
• preserve relationships 7.1 3.0 5.9 2.1 m_iris <- n_iris %>% m_iris %>% transmute(Species,
between observations and 6.3 2.9 5.6 1.8 mutate(model = map(data, mod_fun)) beta = map_dbl(model, b_fun))
subsets of data 6.5 3.0 5.8 2.2

n_iris$data[[3]]
• manipulate many sub-tables 1. MAKE A LIST COLUMN - You can create list columns with functions in the tibble and dplyr packages, as well as tidyr’s nest()
at once with the purrr functions map(), map2(), or pmap().
tibble::tribble(…) tibble::tibble(…) dplyr::mutate(.data, …) Also transmute()
Makes list column when needed Saves list input as list columns Returns list col when result returns list.
Use a two step process to create a nested data frame: tribble( ~max, ~seq, max seq tibble(max = c(3, 4, 5), seq = list(1:3, 1:4, 1:5)) mtcars %>% mutate(seq = map(cyl, seq))
1. Group the data frame into groups with dplyr::group_by() 3, 1:3, 3 <int [3]>

2. Use nest() to create a nested data frame 4, 1:4,


4 <int [4]>

with one row per group S.L S.W P.L P.W 5, 1:5)
5 <int [5]>
tibble::enframe(x, name="name", value="value") dplyr::summarise(.data, …)
5.1 3.5 1.4 0.2 Converts multi-level list to tibble with list cols Returns list col when result is wrapped with list()
Species S.L S.W P.L P.W
setosa 5.1 3.5 1.4 0.2
Species
setosa
S.L S.W P.L P.W
5.1 3.5 1.4 0.2
4.9
4.7
3.0 1.4
3.2 1.3
0.2
0.2
enframe(list('3'=1:3, '4'=1:4, '5'=1:5), 'max', 'seq') mtcars %>% group_by(cyl) %>%
setosa 4.9 3.0 1.4 0.2 setosa 4.9 3.0 1.4 0.2 4.6 3.1 1.5 0.2 summarise(q = list(quantile(mpg)))
setosa 4.7 3.2 1.3 0.2 setosa 4.7 3.2 1.3 0.2 5.0 3.6 1.4 0.2
setosa 4.6 3.1 1.5 0.2 setosa 4.6 3.1 1.5 0.2
setosa 5.0 3.6 1.4 0.2 setosa 5.0 3.6 1.4 0.2 S.L S.W P.L P.W 2. WORK WITH LIST COLUMNS - Use the purrr functions map(), map2(), and pmap() to apply a function that returns a result element-wise
to the cells of a list column. walk(), walk2(), and pwalk() work the same way, but return a side effect.
versi 7.0 3.2 4.7 1.4 versi 7.0 3.2 4.7 1.4 Species data 7.0 3.2 4.7 1.4
versi 6.4 3.2 4.5 1.5 versi 6.4 3.2 4.5 1.5 setos <tibble [50x4]> 6.4 3.2 4.5 1.5
versi versi 6.9 3.1 4.9 1.5 6.9 3.1 4.9 1.5
purrr::map(.x, .f, ...)
6.9 3.1 4.9 1.5 versi <tibble [50x4]>
versi versi 5.5 2.3 4.0 1.3 5.5 2.3 4.0 1.3
fun( , …)
5.5 2.3 4.0 1.3 virgini <tibble [50x4]> data data result
versi
virgini
6.5 2.8 4.6 1.5 versi
virgini
6.5
6.3
2.8
3.3
4.6
6.0
1.5
2.5
6.5 2.8 4.6 1.5
Apply .f element-wise to .x as .f(.x) map( <tibble [50x4]>
, fun, …) fun(
<tibble [50x4]>
, …)
result 1
6.3 3.3 6.0 2.5 <tibble [50x4]> <tibble [50x4]> result 2
virgini 5.8 2.7 5.1 1.9 virgini 5.8 2.7 5.1 1.9 S.L S.W P.L P.W n_iris %>% mutate(n = map(data, dim)) <tibble [50x4]> fun( <tibble [50x4]> , …) result 3
virgini 7.1 3.0 5.9 2.1 virgini 7.1 3.0 5.9 2.1 6.3 3.3 6.0 2.5
virgini 6.3 2.9 5.6 1.8 virgini 6.3 2.9 5.6 1.8 5.8 2.7 5.1 1.9 purrr::map2(.x, .y, .f, ...) data model
virgini 6.5 3.0 5.8 2.2 virgini 6.5 3.0 5.8 2.2 7.1 3.0 5.9 2.1
Apply .f element-wise to .x and .y as .f(.x, .y)
data model
fun( <tibble [50x4]> , <S3: lm> ,…) result

map2( , , fun, …)
<tibble [50x4]> <S3: lm> result 1
6.3 2.9 5.6 1.8 fun( <tibble [50x4]> , <S3: lm> ,…)
n_iris <- iris %>% group_by(Species) %>% nest() 6.5 3.0 5.8 2.2 m_iris %>% mutate(n = map2(data, model, list)) <tibble [50x4]>
<tibble [50x4]>
<S3: lm>
<S3: lm> fun( <tibble [50x4]> , <S3: lm> ,…)
result 2
result 3

tidyr::nest(data, ..., .key = data) purrr::pmap(.l, .f, ...)


data model
For grouped data, moves groups into cells as data frames. Apply .f element-wise to vectors saved in .l data model funs
fun( <tibble [50x4]> , <S3: lm> , funs
,…) result

pmap(list( , , ), fun, …)
<tibble [50x4]> <S3: lm> coef result 1
fun( , , ,…)
coef
m_iris %>% <tibble [50x4]> <S3: lm> AIC <tibble [50x4]> <S3: lm> AIC result 2
mutate(n = pmap(list(data, model, data), list)) <tibble [50x4]> <S3: lm> BIC fun( <tibble [50x4]> , <S3: lm> , BIC ,…) result 3

Unnest a nested data frame Species data Species S.L S.W P.L P.W
setos <tibble [50x4]> setosa 5.1 3.5 1.4 0.2
with unnest(): versi <tibble [50x4]> setosa 4.9 3.0 1.4 0.2 3. SIMPLIFY THE LIST COLUMN (into a regular column)
virgini <tibble [50x4]> setosa 4.7 3.2 1.3 0.2
n_iris %>% unnest() setosa 4.6 3.1 1.5 0.2
Use the purrr functions map_lgl(), purrr::map_lgl(.x, .f, ...) purrr::map_dbl(.x, .f, ...)
versi 7.0 3.2 4.7 1.4
tidyr::unnest(data, ..., .drop = NA, .id=NULL, .sep=NULL) versi 6.4 3.2 4.5 1.5 map_int(), map_dbl(), map_chr(), Apply .f element-wise to .x, return a logical vector Apply .f element-wise to .x, return a double vector
versi 6.9 3.1 4.9 1.5
as well as tidyr’s unnest() to reduce n_iris %>% transmute(n = map_lgl(data, is.matrix)) n_iris %>% transmute(n = map_dbl(data, nrow))
Unnests a nested data frame. versi 5.5 2.3 4.0 1.3
a list column into a regular column. purrr::map_chr(.x, .f, ...)
virgini
virgini
6.3
5.8
3.3
2.7
6.0
5.1
2.5
1.9 purrr::map_int(.x, .f, ...)
virgini 7.1 3.0 5.9 2.1 Apply .f element-wise to .x, return an integer vector Apply .f element-wise to .x, return a character vector
virgini 6.3 2.9 5.6 1.8
n_iris %>% transmute(n = map_int(data, nrow)) n_iris %>% transmute(n = map_chr(data, nrow))
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at purrr.tidyverse.org • purrr 0.2.3 • Updated: 2019-08

Potrebbero piacerti anche