| keep {purrr} | R Documentation |
Keep/discard elements based on their values
Description
keep() selects all elements where .p evaluates to TRUE;
discard() selects all elements where .p evaluates to FALSE.
compact() discards elements where .p evaluates to an empty vector.
Usage
keep(.x, .p, ...)
discard(.x, .p, ...)
compact(.x, .p = identity)
Arguments
.x |
A list or vector. |
.p |
A predicate function (i.e. a function that returns either
|
... |
Additional arguments passed on to |
Details
In other languages, keep() and discard() are often called select()/
filter() and reject()/ drop(), but those names are already taken
in R. keep() is similar to Filter(), but the argument order is more
convenient, and the evaluation of the predicate function .p is stricter.
See Also
keep_at()/discard_at() to keep/discard elements by name.
Examples
rep(10, 10) |>
map(sample, 5) |>
keep(function(x) mean(x) > 6)
# Or use a formula
rep(10, 10) |>
map(sample, 5) |>
keep(\(x) mean(x) > 6)
# Using a string instead of a function will select all list elements
# where that subelement is TRUE
x <- rerun(5, a = rbernoulli(1), b = sample(10))
x
x |> keep("a")
x |> discard("a")
# compact() discards elements that are NULL or that have length zero
list(a = "a", b = NULL, c = integer(0), d = NA, e = list()) |>
compact()