Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally subset a list using the purrr package

Tags:

list

r

subset

purrr

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?

like image 801
Noel Avatar asked May 31 '17 03:05

Noel


2 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
like image 82
austensen Avatar answered Nov 03 '22 00:11

austensen


x[sapply(x, function(x) any(x == 10))]
like image 32
Hong Ooi Avatar answered Nov 03 '22 00:11

Hong Ooi