% 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.
}
