Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass grep() a vector of patterns?

Tags:

regex

r

Is

grep(c(pattern1, pattern2, pattern3), ...)

valid?

like image 784
Phillip Chaffee Avatar asked Dec 14 '25 14:12

Phillip Chaffee


1 Answers

We can illustrate with an example. Here are a few state abbreviations by region.

south <- c('FL', 'TN', 'LA', 'GA')
west <- c('CA', 'NV', 'WA', 'AZ')

Let's look for southern states with 'A' or 'L' in their abbreviations.

y1 <- 'A'
y2 <- 'L'

We could have just written them in to the grep function and separated them with a pipe character |. Or we could practice using variable names. We don't get the correct output if the variables are concatenated.

grep('A|L', south, value=TRUE)
[1] "FL" "LA" "GA"

grep(paste(y1, y2, sep='|'), south, value=TRUE)
[1] "FL" "LA" "GA"

grep(c(y1, y2), south, value=TRUE)
[1] "LA" "GA"
Warning message:
In grep(c(y1, y2), south, value = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used

But there's even more. What if we wanted to find the southern states that have 'L', and western states that have 'A'? We would have to write two functions, right?

mapply(grep, list(y2, y1), list(south, west), value=TRUE)
[[1]]
[1] "FL" "LA"

[[2]]
[1] "CA" "WA" "AZ"

All done in one step.

like image 134
Pierre L Avatar answered Dec 16 '25 17:12

Pierre L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!