Search code examples
rgrepl

Search if a string has two specific words


How do I search if a column of strings has these two words "medication" and "infant" anywhere in the sentence ?

For example if the column contains strings such as

  ID       Col1
  1        Quick Brown fox medication
  2        Brown fox infant
  3        Quick medication fox infant

The expected results should be just row with ID 3

 ID       Col1
  3        Quick medication fox infant

I have tried str_detect and that did not work, so any suggestions is much appreciated.


Solution

  • Base R Approach


    df[with(df, grepl("infant", Col1) & grepl("medication", Col1)),]
    

    It is simple and easy to follow.

    df <-  data.frame(id=c(1,2,3), Col1=c('Quick Brown fox medication',
                                          'Brown fox infant',
                                          'Quick medication fox infant'))