How to filter sentences by keyword

Hello R community, please I need your help. I am trying to filter tweets according to a keyword they contain. The example below illustrates what I am trying to do:

sentences <- c("I love going to buy grocery",
               "It is a long queue at the grocery store",
               "There was a break in transmission",
               "The lady bought a leash for her dog")
df <- data.frame(sentences)

So I have a dataframe of 4 sentences, and I wish to filter out those sentences that contain the word "grocery" in them, which means my program should return the first 2 sentences. Please how can I accomplish this? It seems like it should be a simple task, but I have not figured it out yet. Thanks in anticipation of your help as always.

To return a simple vector:

df[grep("grocery", sentences), ]

A tidyverse method:


df %>% 
  filter(str_detect(sentences, "grocery"))

Like I guessed, it turned out to be a simple solution. Thanks a lot!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.