-1

I have a dataframe that looks like this.

UID    Words
 1     playbook, gold, fun, toxic
 2     play, silver, golden
 3     played, toxicwaste, funny, golden

I need a function which will filter the rows depending on exact match. ie. if I wish to extract rows containing gold, the result will be

UID   Words
 1    playbook, gold, fun, toxic

But if I want rows with golden, the output should be

 UID  Words
  2    play, silver, golden
  3    played, toxicwaste, funny, golden
NinjaR
  • 621
  • 6
  • 22

1 Answers1

0

Assuming your dataframe as df . We can use grep on the Words column to extract the rows with match the given word.

getMatchingRows <- function(x) {
   df[grep(paste0("\\b", x, "\\b"), df$Words),]
}


getMatchingRows("gold")
#  UID                   Words
#1   1 playbook,gold,fun,toxic

getMatchingRows("golden")
#  UID                          Words
#2   2             play,silver,golden
#3   3 played,toxicwaste,funny,golden

getMatchingRows("play")
#  UID              Words
#2   2 play,silver,golden
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213