Matching multiple patterns

Yes, you can. The | in a grep pattern has the same meaning as or. So you can test for your pattern by using "001|100|000" as your pattern. At the same time, grep is vectorised, so all of this can be done in one step:

x <- c("1100", "0010", "1001", "1111")
pattern <- "001|100|000"

grep(pattern, x)
[1] 1 2 3

This returns an index of which of your vectors contained the matching pattern (in this case the first three.)

Sometimes it is more convenient to have a logical vector that tells you which of the elements in your vector were matched. Then you can use grepl:

grepl(pattern, x)
[1]  TRUE  TRUE  TRUE FALSE

See ?regex for help about regular expressions in R.


Edit:
To avoid creating pattern manually we can use paste:

myValues <- c("001", "100", "000")
pattern <- paste(myValues, collapse = "|")

Leave a Comment