R's grepl() to find multiple strings exists

Viewed 53456
grepl("instance|percentage", labelTest$Text)

will return true if any one of instance or percentage is present.

How will I get true only when both the terms are present?

3 Answers

This is how you will get only "TRUE" if both terms do occur in an item of the vector "labelTest$Text". I think this is the exact answer to the question and much shorter than the other solutions.

grepl("instance",labelTest$Text) & grepl("percentage",labelTest$Text)

Use intersect and feed it a grep for each word:

library(data.table) #used for subsetting text vector below

vector_of_text[
  intersect(
    grep(vector_of_text , pattern = "pattern1"),
    grep(vector_of_text , pattern = "pattern2")
  )
]
Related