Noel
Noel

Reputation: 73

How to conditionally subset a list using the purrr package

I have the following list:

x <- list(1:5, 1:10)
x
#> [[1]]
#> [1] 1 2 3 4 5

#> [[2]]
#> [1]  1  2  3  4  5  6  7  8  9 10

and would like to select only the elements which contain 10.

Desired result:

#> [[1]]
#> [1]  1  2  3  4  5  6  7  8  9 10

How can I do this concisely and in a single line using the pipe operator and the purrr package?

The foll. code works, but feels a little clumsy.

x %>% map_lgl(~contains(.,10L)) %>% subset(x,.)

Is there a better way using x and the pipe operator each just once?

Upvotes: 6

Views: 1202

Answers (3)

akrun
akrun

Reputation: 887241

We can use Filter

Filter(function(x) 10 %in% x, x)
#[[1]]
#[1]  1  2  3  4  5  6  7  8  9 10

Or with purrr

x %>%
    purrr::map_lgl(~10 %in% .)  %>%
    x[.]

We can make this a function

filterL <- function(lst, val){
      lst %>%
         purrr::map_lgl(~val %in% .) %>%
        lst[.]
 }

filterL(x, 10)
#[[1]]
# [1]  1  2  3  4  5  6  7  8  9 10

Upvotes: 1

austensen
austensen

Reputation: 3007

You can use purrr::keep

library(purrr)

x <- list(1:5, 1:10)

x

#> [[1]]
#> [1] 1 2 3 4 5
#> 
#> [[2]]
#>  [1]  1  2  3  4  5  6  7  8  9 10

x %>% keep(~ 10 %in% .x)

#> [[1]]
#>  [1]  1  2  3  4  5  6  7  8  9 10

Upvotes: 13

Hong Ooi
Hong Ooi

Reputation: 57686

x[sapply(x, function(x) any(x == 10))]

Upvotes: 2

Related Questions