Agrosel
Agrosel

Reputation: 539

R: Checking if mutliple elements of a vector appear in vector of strings

I'm trying to create a function that checks if all elements of a vector appear in a vector of strings. The test code is presented below:

test_values = c("Alice", "Bob")
test_list = c("Alice,Chris,Mark", "Alice,Bob,Chris", "Alice,Mark,Zach", "Alice,Bob,Mark", "Mark,Bob,Zach", "Alice,Chris,Bob", "Mark,Chris,Zach")

I would like the output for this to be FALSE TRUE FALSE TRUE FALSE TRUE FALSE.

I first thought I'd be able to switch the | to & in the command grepl(paste(test_values, collapse='|'), test_list) to get when Alice and Bob are both in the string instead of when either of them appear, but I was unable to get the correct answer.

I also would rather not use the command: grepl(test_values[1], test_list) & grepl(test_values[2], test_list) because the test_values vector will change dynamically (varying from length 0 to 3), so I'm looking for something to take that into account.

Upvotes: 3

Views: 69

Answers (1)

akrun
akrun

Reputation: 887891

We can use Reduce with grepl

Reduce(`&`, lapply(test_values, grepl, test_list))
#[1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE

Upvotes: 8

Related Questions