简体   繁体   中英

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?

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
x[sapply(x, function(x) any(x == 10))]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM