% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/keep.R
\name{keep}
\alias{keep}
\alias{discard}
\alias{compact}
\title{Keep/discard elements based on their values}
\usage{
keep(.x, .p, ...)

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

compact(.x, .p = identity)
}
\arguments{
\item{.x}{A list or vector.}

\item{.p}{A predicate function (i.e. a function that returns either \code{TRUE}
or \code{FALSE}) specified in one of the following ways:
\itemize{
\item A named function, e.g. \code{is.character}.
\item An anonymous function, e.g. \verb{\\(x) all(x < 0)} or \code{function(x) all(x < 0)}.
\item A formula, e.g. \code{~ all(.x < 0)}. Use \code{.x} to refer to the first argument.
No longer recommended.
}}

\item{...}{Additional arguments passed on to \code{.p}.}
}
\description{
\code{keep()} selects all elements where \code{.p} evaluates to \code{TRUE};
\code{discard()} selects all elements where \code{.p} evaluates to \code{FALSE}.
\code{compact()} discards elements where \code{.p} evaluates to an empty vector.
}
\details{
In other languages, \code{keep()} and \code{discard()} are often called \code{select()}/
\code{filter()} and \code{reject()}/ \code{drop()}, but those names are already taken
in R. \code{keep()} is similar to \code{\link[=Filter]{Filter()}}, but the argument order is more
convenient, and the evaluation of the predicate function \code{.p} is stricter.
}
\examples{
rep(10, 10) |>
  map(sample, 5) |>
  keep(function(x) mean(x) > 6)

# Or use shorthand form
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()
}
\seealso{
\code{\link[=keep_at]{keep_at()}}/\code{\link[=discard_at]{discard_at()}} to keep/discard elements by name.
}
