# keep: Keep or discard elements using a predicate function. In purrr: Functional Programming Tools

## Description

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

## Usage

 ```1 2 3 4 5``` ```keep(.x, .p, ...) discard(.x, .p, ...) compact(.x, .p = identity) ```

## Arguments

 `.x` A list or vector. `.p` 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

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15``` ```rep(10, 10) %>% map(sample, 5) %>% keep(function(x) mean(x) > 6) # Or use a formula rep(10, 10) %>% map(sample, 5) %>% keep(~ mean(.x) > 6) # 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 x %>% keep("a") x %>% discard("a") ```

### Example output

```[[1]]
[1]  6  2  9  7 10

[[2]]
[1] 8 7 9 4 3

[[3]]
[1]  4  2  9  8 10

[[1]]
[1]  8 10  7  4  9

[[2]]
[1]  5  8  7  1 10

[[3]]
[1]  2 10  9  7  5

[[4]]
[1]  9 10  5  6  8

[[1]]
[[1]]\$a
[1] FALSE

[[1]]\$b
[1]  1  2  7  9  5 10  8  3  6  4

[[2]]
[[2]]\$a
[1] FALSE

[[2]]\$b
[1]  3  8  7  9  2  6  5  4  1 10

[[3]]
[[3]]\$a
[1] TRUE

[[3]]\$b
[1] 10  5  6  1  4  8  3  7  9  2

[[4]]
[[4]]\$a
[1] FALSE

[[4]]\$b
[1]  4  7  1  9  8  3 10  5  6  2

[[5]]
[[5]]\$a
[1] FALSE

[[5]]\$b
[1]  6  5  3  2 10  9  8  4  7  1

[[1]]
[[1]]\$a
[1] TRUE

[[1]]\$b
[1] 10  5  6  1  4  8  3  7  9  2

[[1]]
[[1]]\$a
[1] FALSE

[[1]]\$b
[1]  1  2  7  9  5 10  8  3  6  4

[[2]]
[[2]]\$a
[1] FALSE

[[2]]\$b
[1]  3  8  7  9  2  6  5  4  1 10

[[3]]
[[3]]\$a
[1] FALSE

[[3]]\$b
[1]  4  7  1  9  8  3 10  5  6  2

[[4]]
[[4]]\$a
[1] FALSE

[[4]]\$b
[1]  6  5  3  2 10  9  8  4  7  1
```

purrr documentation built on Nov. 17, 2017, 7:35 a.m.