1

I want to check if any of a set of "keywords" appear in a string. So, for "text" below, the result should be TRUE (or 1), and for text_2 it should be FALSE (or 0).

keywords <- c("one", "two", "three", "four") #set of keywords
text <- "Blah blah one blah two" 
text_2 <- "Blah blah" 

I tried some variations on str_detect, but I got stuck.

So, for instance, and I know I'm not using this function correctly but:

> keywords <- c("motor", "car", "ford") #list of keywords
> text <- "I am looking to buy a ford" #string I'd like to check
> ifelse(str_detect(text, pattern = keywords), 1, 0)
[1] 0 0 1

Is there a better approach?

wimlouw
  • 13
  • 3

1 Answers1

1

Try this...

any(sapply(keywords,grepl,text))
[1] TRUE

any(sapply(keywords,grepl,text_2))
[1] FALSE
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32