-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathdetect.Rd
More file actions
73 lines (60 loc) · 2.17 KB
/
detect.Rd
File metadata and controls
73 lines (60 loc) · 2.17 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
64
65
66
67
68
69
70
71
72
73
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/detect.R
\name{detect}
\alias{detect}
\alias{detect_index}
\title{Find the value or position of the first match}
\usage{
detect(.x, .f, ..., .dir = c("forward", "backward"), .default = NULL)
detect_index(.x, .f, ..., .dir = c("forward", "backward"))
}
\arguments{
\item{.x}{A list or vector.}
\item{.f}{A function, specified in one of the following ways:
\itemize{
\item A named function, e.g. \code{mean}.
\item An anonymous function, e.g. \verb{\\(x) x + 1} or \code{function(x) x + 1}.
\item A formula, e.g. \code{~ .x + 1}. Use \code{.x} to refer to the first argument. No
longer recommended.
\item A string, integer, or list, e.g. \code{"idx"}, \code{1}, or \code{list("idx", 1)} which
are shorthand for \verb{\\(x) pluck(x, "idx")}, \verb{\\(x) pluck(x, 1)}, and
\verb{\\(x) pluck(x, "idx", 1)} respectively. Optionally supply \code{.default} to
set a default value if the indexed element is \code{NULL} or does not exist.
}}
\item{...}{Additional arguments passed on to \code{.p}.}
\item{.dir}{If \code{"forward"}, the default, starts at the beginning of
the vector and move towards the end; if \code{"backward"}, starts at
the end of the vector and moves towards the beginning.}
\item{.default}{The value returned when nothing is detected.}
}
\value{
\code{detect} the value of the first item that matches the
predicate; \code{detect_index} the position of the matching item.
If not found, \code{detect} returns \code{NULL} and \code{detect_index}
returns 0.
}
\description{
Find the value or position of the first match
}
\examples{
is_even <- function(x) x \%\% 2 == 0
3:10 |> detect(is_even)
3:10 |> detect_index(is_even)
3:10 |> detect(is_even, .dir = "backward")
3:10 |> detect_index(is_even, .dir = "backward")
# Since `.f` is passed to as_mapper(), you can supply a pluck object:
x <- list(
list(1, foo = FALSE),
list(2, foo = TRUE),
list(3, foo = TRUE)
)
detect(x, "foo")
detect_index(x, "foo")
# If you need to find all values, use keep():
keep(x, "foo")
# If you need to find all positions, use map_lgl():
which(map_lgl(x, "foo"))
}
\seealso{
\code{\link[=keep]{keep()}} for keeping all matching values.
}