keep

0th

Percentile

Keep or discard elements using a predicate function.

keep and discard are opposites. compact is a handy wrapper that removes all elements that are NULL.

Usage
keep(.x, .p, ...)discard(.x, .p, ...)compact(.x, .p = identity)
Arguments
.x

A list or vector.

.p

A single predicate function, a formula describing such a predicate function, or a logical vector of the same length as .x. Alternatively, if the elements of .x are themselves lists of objects, a string indicating the name of a logical element in the inner lists. Only those elements where .p evaluates to TRUE will be modified.

...

Additional arguments passed on to .p.

Details

These are usually called select or filter and reject or drop, but those names are already taken. keep is similar to Filter() but the argument order is more convenient, and the evaluation of .f is stricter.

• keep
• compact
Examples
# NOT RUN {
rep(10, 10) %>%
map(sample, 5) %>%
keep(function(x) mean(x) > 6)

# Or use a formula
rep(10, 10) %>%
map(sample, 5) %>%
keep(~ 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")