keep() and discard() are opposites. compact() is a handy wrapper that removes all empty elements.

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

discard(.x, .p, ...)

compact(.x, .p = identity)

Arguments

.x

A list or vector.

.p

For keep() and discard(), a predicate function. Only those elements where .p evaluates to TRUE will be kept or discarded.

For compact(), a function that is applied to each element of .x. Only those elements where .p evaluates to an empty vector will be discarded.

...

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 the predicate function .p 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 #> #>
x %>% discard("a")
#> [[1]] #> [[1]]$a #> [1] FALSE #> #> [[1]]$b #> [1] 1 4 6 3 9 10 5 7 2 8 #> #>
# compact() discards elements that are NULL or that have length zero list(a = "a", b = NULL, c = integer(0), d = NA, e = list()) %>% compact()
#> $a #> [1] "a" #> #> $d #> [1] NA #>