grep using a character vector with multiple patterns
In addition to @Marek's comment about not including fixed==TRUE
, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6"
.
You also mention that there are lots of patterns. Assuming that they are in a vector
toMatch <- c("A1", "A9", "A6")
Then you can create your regular expression directly using paste
and collapse = "|"
.
matches <- unique (grep(paste(toMatch,collapse="|"), myfile$Letter, value=TRUE))
Good answers, however don't forget about filter()
from dplyr:
patterns <- c("A1", "A9", "A6")>your_df FirstName Letter1 Alex A12 Alex A63 Alex A74 Bob A15 Chris A96 Chris A6result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))>result FirstName Letter1 Alex A12 Alex A63 Bob A14 Chris A95 Chris A6