keep and discard are opposites. compact is a handy wrapper that removes all elements that are NULL.

keep(.x, .p, ...)

compact(.x, .p = identity)

## Arguments

.x A list or vector. A single predicate function, a formula describing such a predicate function, or a logical vector of the same length as .x. Alternatively, if the elements of .x are themselves lists of objects, a string indicating the name of a logical element in the inner lists. Only those elements where .p evaluates to TRUE will be modified. Additional arguments passed on to .p.

## Details

These are usually called select or filter and reject or drop, but those names are already taken. keep is similar to Filter() but the argument order is more convenient, and the evaluation of .f is stricter.

## Examples

rep(10, 10) %>%
map(sample, 5) %>%
keep(function(x) mean(x) > 6)#> [[1]]
#> [1]  9  6 10  2  7
#>
#> [[2]]
#> [1]  2  9  8 10  6
#>
#> [[3]]
#> [1]  1  8  4 10  9
#>
#> [[4]]
#> [1] 10  8  5  9  3
#>
# Or use a formula
rep(10, 10) %>%
map(sample, 5) %>%
keep(~ mean(.x) > 6)#> list()
# Using a string instead of a function will select all list elements
# where that subelement is TRUE
x <- rerun(5, a = rbernoulli(1), b = sample(10))
x#> [[1]]
#> [[1]]$a #> [1] TRUE #> #> [[1]]$b
#>  [1]  6  4  5  1 10  9  8  2  3  7
#>
#>
#> [[2]]
#> [[2]]$a #> [1] TRUE #> #> [[2]]$b
#>  [1]  7  4  3  6  8  1  9 10  5  2
#>
#>
#> [[3]]
#> [[3]]$a #> [1] TRUE #> #> [[3]]$b
#>  [1]  7 10  9  2  8  1  3  4  6  5
#>
#>
#> [[4]]
#> [[4]]$a #> [1] FALSE #> #> [[4]]$b
#>  [1]  1  4  6  3  9 10  5  7  2  8
#>
#>
#> [[5]]
#> [[5]]$a #> [1] TRUE #> #> [[5]]$b
#>  [1]  1  7 10  8  5  3  6  2  4  9
#>
#> x %>% keep("a")#> [[1]]
#> [[1]]$a #> [1] TRUE #> #> [[1]]$b
#>  [1]  6  4  5  1 10  9  8  2  3  7
#>
#>
#> [[2]]
#> [[2]]$a #> [1] TRUE #> #> [[2]]$b
#>  [1]  7  4  3  6  8  1  9 10  5  2
#>
#>
#> [[3]]
#> [[3]]$a #> [1] TRUE #> #> [[3]]$b
#>  [1]  7 10  9  2  8  1  3  4  6  5
#>
#>
#> [[4]]
#> [[4]]$a #> [1] TRUE #> #> [[4]]$b
#>  [1]  1  7 10  8  5  3  6  2  4  9
#>
#> [[1]]$a #> [1] FALSE #> #> [[1]]$b
#>