detect: Find the value or position of the first match

Description Usage Arguments Value See Also Examples

View source: R/detect.R

Description

Find the value or position of the first match

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
detect(
  .x,
  .f,
  ...,
  .dir = c("forward", "backward"),
  .right = NULL,
  .default = NULL
)

detect_index(.x, .f, ..., .dir = c("forward", "backward"), .right = NULL)

Arguments

.x

A list or atomic vector.

.f

A function, formula, or vector (not necessarily atomic).

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function. There are three ways to refer to the arguments:

  • For a single argument function, use .

  • For a two argument function, use .x and .y

  • For more arguments, use ..1, ..2, ..3 etc

This syntax allows you to create very compact anonymous functions.

If character vector, numeric vector, or list, it is converted to an extractor function. Character vectors index by name and numeric vectors index by position; use a list to index by position and name at different levels. If a component is not present, the value of .default will be returned.

...

Additional arguments passed on to the mapped function.

.dir

If "forward", the default, starts at the beginning of the vector and move towards the end; if "backward", starts at the end of the vector and moves towards the beginning.

.right

Soft-deprecated. Please use .dir instead.

.default

The value returned when nothing is detected.

Value

detect the value of the first item that matches the predicate; detect_index the position of the matching item. If not found, detect returns NULL and detect_index returns 0.

See Also

keep() for keeping all matching values.

Examples

 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
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
# lambda-formula or 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"))

Example output

[1] 4
[1] 2
[1] 10
[1] 8
[[1]]
[1] 2

$foo
[1] TRUE

[1] 2
[[1]]
[[1]][[1]]
[1] 2

[[1]]$foo
[1] TRUE


[[2]]
[[2]][[1]]
[1] 3

[[2]]$foo
[1] TRUE


[1] 2 3

purrr documentation built on April 19, 2020, 4:17 p.m.