purrr::discard
discard() removes elements from a list or vector where your predicate returns TRUE. It’s the mirror image of keep() — where keep() retains matches, discard() drops them.
Basic Usage
library(purrr)
x <- list(a = 1:3, b = "hello", c = 4:6, d = "world")
discard(x, is.numeric)
#> $b
#> [1] "hello"
#>
#> $d
#> [1] "world"
Compare to keep() which does the opposite:
keep(x, is.numeric)
#> $a
#> [1] 1 2 3
#>
#> $c
#> [1] 4 5 6
Predicate Syntax
The .p argument works the same way as in keep():
Named function:
discard(x, is.character)
Anonymous function:
discard(x, \(elem) length(elem) > 2)
String shorthand for lists — drops elements where the named sub-element is falsy:
z <- list(
list(name = "alice", active = TRUE),
list(name = "bob", active = FALSE),
list(name = "carol", active = TRUE)
)
discard(z, "active")
#> [[1]]
#> $name
#> [1] "bob"
Additional Arguments
Pass extra arguments to your predicate with ...:
nums <- list(a = c(1, 2, 3), b = c(4, 5), c = c(6, 7, 8, 9))
discard(nums, \(x) mean(x) > 4)
#> $a
#> [1] 1 2 3
Pipe-Friendly Chaining
library(dplyr)
mtcars %>%
split(.$cyl) %>%
discard(\(df) nrow(df) <= 10) %>%
map(dim)
Relationship to keep() and compact()
| Function | Keeps elements where predicate… | Removes elements where predicate… |
|---|---|---|
keep() | returns TRUE | returns FALSE |
discard() | returns FALSE | returns TRUE |
compact() | — | is empty or NULL |
See Also
- /reference/tidyverse/purrr-keep/ — retain elements that match a predicate
- /reference/tidyverse/purrr-map/ — transform each element with
map() - /guides/purrr-functional-programming/ — functional programming patterns with purrr