Renat
Renat

Reputation: 35

How to filter a list of tibbles based on a string and get whole tibble with a string, not a particular row?

I have a list of tibbles.

library(tidyverse)
mylist <- list(tibble(x = 1:5),tibble(x = 6:10),tibble(x = 11:15))

I want to filter them based on a particular values and get a list with whole tibbles, where this value is present.

I have already tried lapply and map, but they filter the tibble too, not just the list.

b <- map(mylist, ~filter(.x,  x==3|x==6))

c <- lapply(mylist, function(df){
  df %>%
    filter(x == 3|x==6)
})

These two methods do not work, as they return only 3 and 6, not the whole tibbles (1:5 and 6:10). Also I want to output list to exclude empty tibbles, so that final list has length of 2.

Upvotes: 1

Views: 451

Answers (1)

akrun
akrun

Reputation: 887621

We may need any to extract the list elements as a whole

mylist[sapply(mylist, function(x) any(c(3, 6) %in% x$x))]

Or with Filter

Filter(function(y) any(c(3,6) %in% y$x), mylist)

Or using tidyverse

library(tidyverse)
keep(mylist, ~ any(c(3, 6) %in% .x$x))
#[[1]]
# A tibble: 5 x 1
#      x
#  <int>
#1     1
#2     2
#3     3
#4     4
#5     5

#[[2]]
# A tibble: 5 x 1
#      x
#  <int>
#1     6
#2     7
#3     8
#4     9
#5    10

Upvotes: 1

Related Questions