rguides

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()

FunctionKeeps elements where predicate…Removes elements where predicate…
keep()returns TRUEreturns FALSE
discard()returns FALSEreturns TRUE
compact()is empty or NULL

See Also