keep_at() and discard_at()

purrr 1.1.0

purrr
purrr has two new functions, keep_at() and discard_at(), that operate on names.
Published

December 20, 2022

Install purrr 1.0.0 with:

pak::pak("cran/purrr@1.0.0")

Load the package with:

keep_at() and discard_at()

purrr has two functions, keep() and discard(), that keep/discard elements by value:

rep(10, 10) |>
  map(sample, 5) |>
  keep(function(x) mean(x) > 6)
[[1]]
[1]  9 10  3  6  5

[[2]]
[1]  6 10  1  8  9
rep(10, 10) |>
  map(sample, 5) |>
  discard(function(x) mean(x) > 6)
[[1]]
[1] 4 5 7 2 6

[[2]]
[1] 9 7 3 1 8

[[3]]
[1] 2 9 6 8 4

[[4]]
[1] 2 4 5 7 6

[[5]]
[1]  4  7 10  3  1

[[6]]
[1] 6 5 2 4 7

purrr has two new functions, keep_at() and discard_at(), that work like keep() and discard() but operate on names rather than values:

x <- list(a = 1, b = 2, c = 3, D = 4, E = 5)

x |> 
  keep_at(c("a", "b", "c")) |> 
  str()
List of 3
 $ a: num 1
 $ b: num 2
 $ c: num 3
x |> 
  discard_at(c("a", "b", "c")) |> 
  str()
List of 2
 $ D: num 4
 $ E: num 5

Or, you can provide a logical vector

is_lower_case <- function(x) x == tolower(x)

x |> keep_at(is_lower_case)
$a
[1] 1

$b
[1] 2

$c
[1] 3

Learn more