How to conditionally multiply a list using 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 items containing 10.

Desired Result:

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

How can I do this briefly and on one line using the pipe operator and purrr package?

. the code works but feels a little awkward.

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

Is there a better way to use xa pipe operator every time?

+4
source share
3 answers

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

We can use Filter

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

Or using purrr

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

We can make it 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
+1
source

Source: https://habr.com/ru/post/1678215/


All Articles