keep | R Documentation |
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)
.x |
A list or vector. |
.p |
A predicate function (i.e. a function that returns either
|
... |
Additional arguments passed on to |
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.
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 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()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.