Joe
Joe

Reputation: 1768

Return all elements of list containing certain strings

I have a list of vectors containing strings and I want R to give me another list with all vectors that contain certain strings. MWE:

list1 <- list("a", c("a", "b"), c("a", "b", "c"))

Now, I want a list that contains all vectors with "a" and "b" in it. Thus, the new list should contain two elements, c("a", "b") and c("a", "b", "c").

As list1[grep("a|b", list1)] gives me a list of all vectors containing either "a" or "b", I expected list1[grep("a&b", list1)] to do what I want, but it did not (it returned a list of length 0).

Upvotes: 1

Views: 1222

Answers (4)

user1981275
user1981275

Reputation: 13372

A solution with grepl:

> list1[grepl("a", list1) & grepl("b", list1)]
[[1]]
[1] "a" "b"

[[2]]
[1] "a" "b" "c"

Upvotes: 1

akrun
akrun

Reputation: 887501

We can use Filter

Filter(function(x) all(c('a', 'b') %in% x), test)
#[[1]]
#[1] "a" "b"

#[[2]]
#[1] "a" "b" "c"

Upvotes: 1

Iaroslav Domin
Iaroslav Domin

Reputation: 2718

Try purrr::keep

library(purrr)
keep(list1, ~ all(c("a", "b") %in% .))

Upvotes: 2

amatsuo_net
amatsuo_net

Reputation: 2448

This should work:

test <- list("a", c("a", "b"), c("a", "b", "c"))
test[sapply(test, function(x) sum(c('a', 'b') %in% x) == 2)]

Upvotes: 2

Related Questions