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)
.x | A list or vector. |
---|---|
.p | For For |
... | Additional arguments passed on to |
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.
#> [[1]] #> [1] 6 10 7 8 5 #> #> [[2]] #> [1] 5 10 6 9 2 #> #> [[3]] #> [1] 9 10 2 7 5 #> #> [[4]] #> [1] 9 7 2 10 5 #>#> [[1]] #> [1] 10 9 6 4 7 #> #> [[2]] #> [1] 8 2 7 5 10 #># 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] 1 9 5 8 7 2 4 6 10 3 #> #> #> [[2]] #> [[2]]$a #> [1] FALSE #> #> [[2]]$b #> [1] 3 8 7 6 9 2 1 4 10 5 #> #> #> [[3]] #> [[3]]$a #> [1] TRUE #> #> [[3]]$b #> [1] 9 10 3 6 2 1 7 8 4 5 #> #> #> [[4]] #> [[4]]$a #> [1] TRUE #> #> [[4]]$b #> [1] 7 4 3 8 10 5 2 9 6 1 #> #> #> [[5]] #> [[5]]$a #> [1] TRUE #> #> [[5]]$b #> [1] 7 6 2 9 5 8 10 1 3 4 #> #>x %>% keep("a")#> [[1]] #> [[1]]$a #> [1] TRUE #> #> [[1]]$b #> [1] 1 9 5 8 7 2 4 6 10 3 #> #> #> [[2]] #> [[2]]$a #> [1] TRUE #> #> [[2]]$b #> [1] 9 10 3 6 2 1 7 8 4 5 #> #> #> [[3]] #> [[3]]$a #> [1] TRUE #> #> [[3]]$b #> [1] 7 4 3 8 10 5 2 9 6 1 #> #> #> [[4]] #> [[4]]$a #> [1] TRUE #> #> [[4]]$b #> [1] 7 6 2 9 5 8 10 1 3 4 #> #>x %>% discard("a")#> [[1]] #> [[1]]$a #> [1] FALSE #> #> [[1]]$b #> [1] 3 8 7 6 9 2 1 4 10 5 #> #># 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 #>