The purrr package makes it easy to work with lists and functions. This cheatsheet will remind you how to manipulate lists with purrr as well as how to apply functions iteratively to each element of a list or vector. The back of the cheatsheet explains how to work with list-columns. With list columns, you can use a simple data frame to organize any collection of objects in R.
Map functions apply a function iteratively to each element of a list or vector.
x = c(TRUE,TRUE,FALSE)
map(x, is.logical)
map2(x, y, sum)
pmap(list(x, y, z), sum, na.rm = TRUE)
l <- list(var, sd);
invoke_map(l, x = 1:9)
lmap(.x, .f, …) Apply function to each list-element of a list or vector.
imap(.x, .f, …) Apply .f to each element of a list or vector and its index.
map(), map2(), pmap(), imap and invoke_map each return a list. Use a suffixed version to return the results as a specific type of flat vector, e.g. map2_chr, pmap_lgl, etc.
Use walk, walk2, and pwalk to trigger side effects. Each return its input invisibly.
function | returns |
---|---|
map | list |
map_chr | character vector |
map_dbl | double (numeric) vector |
map_dfc | data frame (column bind) |
map_dfr | data frame (row bind) |
map_int | integer vector |
map_lgl | logical vector |
walk | triggers side effects, returns the input invisibly |
pluck(x,"b",attr_getter("n"))
keep(x, is.na)
discard(x, is.na)
compact(x)
head_while(x, is.character)
every(x, is.character)
some(x, is.character)
has_element(x, "foo")
detect(x, is.character)
detect_index(x, is.character)
vec_depth(x)
modify(x, ~.+ 2)
modify_at(x, "b", ~.+ 2)
modify_if(x, is.numeric,~.+2)
modify_depth(x, 1, ~.+ 2)
flatten(x)
transpose(x)
append(x, list(d = 1))
prepend(x, list(d = 1))
*splice(…) Combine objects into a list, storing S3 objects as sub-lists.
splice(x, y, "foo")
array_tree(x, margin = 3)
cross2(1:3, 4:6)
set_names(x, c("p", "q", "r"))
set_names(x, tolower)
reduce(x, sum)
accumulate(x, sum)
compose() Compose multiple functions.
lift() Change the type of input a function takes. Also lift_dl, lift_dv, lift_ld, lift_lv, lift_vd, lift_vl.
rerun() Rerun expression n times.
negate() Negate a predicate function (a pipe friendly !)
partial() Create a version of a function that has some args preset to values.
safely() Modify func to return list of results and errors.
quietly() Modify function to return list of results, output, messages, warnings.
possibly() Modify function to return default value whenever an error occurs (instead of error).