-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathkeep.Rd
More file actions
63 lines (56 loc) · 1.97 KB
/
keep.Rd
File metadata and controls
63 lines (56 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
% 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.
}