How can I return a boolean when a variable contains any one of the elements of my vector?

Viewed 179

I have a vector:

v <- c("apple","banana","orange")

I want to search a column in my dataset and return either TRUE or FALSE if any of the elements of v are present.

As an example:

mystring <- "I have a grape but I have nothing else except an apple"  

The solution I came up with is to use str_count to count the number of times my vector elements appear in mystring and then mutate based on the counts to get my boolean values -- ie, using case_when count > 0 and count == 0).

This seems like a poor approach. I'd really appreciate some guidance on a better way to do this.

2 Answers

We can paste the elements in 'v' to a single string and use str_detect

library(stringr)
str_detect(mystring, str_c("\\b(", str_c(v, collapse="|"), ")\\b"))
[1] TRUE

We could create a pattern then use grepl:

pattern <- paste(v, collapse = "|")
grepl(pattern, mystring)

[1] TRUE
Related