| lmap | R Documentation |
lmap(), lmap_at() and lmap_if() are similar to map(), map_at() and
map_if(), except instead of mapping over .x[[i]], they instead map over
.x[i].
This has several advantages:
It makes it possible to work with functions that exclusively take a list.
It allows .f to access the attributes of the encapsulating list,
like names().
It allows .f to return a larger or small list than it receives
changing the size of the output.
lmap(.x, .f, ...)
lmap_if(.x, .p, .f, ..., .else = NULL)
lmap_at(.x, .at, .f, ...)
A list or data frame, matching .x. There are no guarantees about
the length.
Other map variants:
imap(),
map(),
map2(),
map_depth(),
map_if(),
modify(),
pmap()
set.seed(1014)
# Let's write a function that returns a larger list or an empty list
# depending on some condition. It also uses the input name to name the
# output
maybe_rep <- function(x) {
n <- rpois(1, 2)
set_names(rep_len(x, n), paste0(names(x), seq_len(n)))
}
# The output size varies each time we map f()
x <- list(a = 1:4, b = letters[5:7], c = 8:9, d = letters[10])
x |> lmap(maybe_rep) |> str()
# We can apply f() on a selected subset of x
x |> lmap_at(c("a", "d"), maybe_rep) |> str()
# Or only where a condition is satisfied
x |> lmap_if(is.character, maybe_rep) |> str()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.