-1

I have created a column of paths on R that looks like this:

Path
Adam > Bob > Jeff
Bob > Sarah > Kevin
Adam > Sarah > Kevin
Jeff > Adam > Bob
Adam > Kevin > Jeff

How do I filter the column, so It just has the paths involving Jeff:

Path
Adam > Bob > Jeff
Jeff > Adam > Bob
Adam > Kevin > Jeff
deez
  • 50
  • 8

1 Answers1

1

We can use grep either using [ (For [, by default drop = TRUE - therefore, we need to change it to drop = FALSE to avoid the one column/one row datasets converted to vector)

df1[grep("\\bJeff\\b", df1$Path, ignore.case = TRUE),, drop = FALSE]

or with subset, we don't have to use the drop = FALSE as it is by default FALSE

subset(df1, grepl("\\bJeff\\b", Path, ignore.case = TRUE))
#                 Path
#1   Adam > Bob > Jeff
#4   Jeff > Adam > Bob
#5 Adam > Kevin > Jeff

The pattern we match would be "Jeff", but to make it more stringent i.e. not to match "Jeffy" or "Jefferson", we can add the word boundary (\\b) before and after the word.

akrun
  • 874,273
  • 37
  • 540
  • 662