keep: Keep/discard elements based on their values

View source: R/keep.R

keepR Documentation

Keep/discard elements based on their values


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.


keep(.x, .p, ...)

discard(.x, .p, ...)

compact(.x, .p = identity)



A list or vector.


A predicate function (i.e. a function that returns either TRUE or FALSE) specified in one of the following ways:

  • A named function, e.g. is.character.

  • An anonymous function, e.g. \(x) all(x < 0) or function(x) all(x < 0).

  • A formula, e.g. ~ all(.x < 0). You must use .x to refer to the first argument). Only recommended if you require backward compatibility with older versions of R.


Additional arguments passed on to .p.


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.


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 |> 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()) |>

purrr documentation built on Jan. 10, 2023, 5:15 p.m.