0Pricing
R Academy · Lesson

keep(), discard(), and List Filtering

Filter list elements by predicate functions for clean pipelines.

Filtering Lists with purrr

purrr provides a family of functions for filtering, searching, and testing lists based on predicates. A predicate is a function that returns TRUE or FALSE. These functions replace verbose Filter() calls and conditional loops.

library(purrr)

# A mixed list to filter
mixed <- list(1L, 'hello', 3.14, NULL, TRUE, 42L, 'world', NULL)

cat('Total elements:', length(mixed), '\n')
cat('Non-NULL elements:', length(compact(mixed)))

keep() — Keep Elements Matching a Predicate

keep(.x, .p) keeps only elements of .x for which the predicate .p returns TRUE. It is the opposite of discard(). The predicate can be a function name, a formula, or a logical vector.

library(purrr)

mixed <- list(1L, 'hello', 3.14, TRUE, 42L, 'world', 2.7)

# Keep only numeric values
numeric_only <- keep(mixed, is.numeric)
print(numeric_only)

# Keep values greater than 5
keep(mixed, ~is.numeric(.x) && .x > 5)

All lessons in this course

  1. map() and Typed Variants
  2. map2() and pmap() for Multiple Inputs
  3. reduce(), accumulate(), and walk()
  4. keep(), discard(), and List Filtering
← Back to R Academy