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

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

compact(.x, .p = identity)

## Arguments

.x A list or vector. 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] 4 9 6 5 7
#>
#> [[2]]
#> [1] 9 8 3 6 7
#>
# Or use a formula
rep(10, 10) %>%
map(sample, 5) %>%
keep(~ mean(.x) > 6)#> [[1]]
#> [1]  4  8  9  7 10
#>
#> [[2]]
#> [1]  8  4  9 10  5
#>
#> [[3]]
#> [1]  9  7 10  8  5
#>
#> [[4]]
#> [1]  3 10  8  9  4
#>
#> [[5]]
#> [1] 10  7  9  6  2
#>
# 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] FALSE #> #> [[1]]$b
#>  [1]  4  3  7 10  8  9  1  5  2  6
#>
#>
#> [[2]]
#> [[2]]$a #> [1] FALSE #> #> [[2]]$b
#>  [1]  5  9  3  1  6  4  7 10  2  8
#>
#>
#> [[3]]
#> [[3]]$a #> [1] TRUE #> #> [[3]]$b
#>  [1]  4  6  7  9 10  1  3  2  5  8
#>
#>
#> [[4]]
#> [[4]]$a #> [1] TRUE #> #> [[4]]$b
#>  [1]  1  6  9  4  8  3 10  5  2  7
#>
#>
#> [[5]]
#> [[5]]$a #> [1] TRUE #> #> [[5]]$b
#>  [1]  4  9  7  2  6 10  5  1  8  3
#>
#> x %>% keep("a")#> [[1]]
#> [[1]]$a #> [1] TRUE #> #> [[1]]$b
#>  [1]  4  6  7  9 10  1  3  2  5  8
#>
#>
#> [[2]]
#> [[2]]$a #> [1] TRUE #> #> [[2]]$b
#>  [1]  1  6  9  4  8  3 10  5  2  7
#>
#>
#> [[3]]
#> [[3]]$a #> [1] TRUE #> #> [[3]]$b
#>  [1]  4  9  7  2  6 10  5  1  8  3
#>
#> [[1]]$a #> [1] FALSE #> #> [[1]]$b
#>  [1]  4  3  7 10  8  9  1  5  2  6
#>
#>
#> [[2]]
#> [[2]]$a #> [1] FALSE #> #> [[2]]$b
#>  [1]  5  9  3  1  6  4  7 10  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
#>