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))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With