Find the value or position of the first match
detect(.x, .f, ..., .dir = c("forward", "backward"), .right = NULL, .default = NULL) detect_index(.x, .f, ..., .dir = c("forward", "backward"), .right = NULL)
.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.
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 |
... | Additional arguments passed on to the mapped function. |
.dir | If |
.right | Soft-deprecated. Please use |
.default | The value returned when nothing is detected. |
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.
keep()
for keeping all matching values.
is_even <- function(x) x %% 2 == 0 3:10 %>% detect(is_even)#> [1] 43:10 %>% detect_index(is_even)#> [1] 23:10 %>% detect(is_even, .dir = "backward")#> [1] 103:10 %>% detect_index(is_even, .dir = "backward")#> [1] 8# 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")#> [[1]] #> [1] 2 #> #> $foo #> [1] TRUE #>detect_index(x, "foo")#> [1] 2#> [[1]] #> [[1]][[1]] #> [1] 2 #> #> [[1]]$foo #> [1] TRUE #> #> #> [[2]] #> [[2]][[1]] #> [1] 3 #> #> [[2]]$foo #> [1] TRUE #> #>#> [1] 2 3