[R] Using gregexpr with multiple search elements

Corey Sparks corey.sparks at UTSA.EDU
Wed Feb 25 17:50:04 CET 2009

Dear list,
I am trying to use gregexpr to see if entries in a dataframe have  
either of two possible values for a string.
here's an example
text<-c("fat", "rat", "cat", "dog", "log", "fish")

If I just wanted to find if any one of the elements in text match the  
pattern "at" I would do
gregexpr("\\at", text)

which would match on the first three elements, you can do something like
ifelse(gregexpr("\\at",text)>-1, 1,0)

to see if a particular entry in the data "text" is matched.
My problem is I need to check if either of two patterns match in the  
data, an example that doesn't work is
gregexpr(c("\\at", "\\og"), text)

which is the basic form of what I'm looking to do, if this would work  
I would get a match for elements 1 through 5 of text, since either  
"at" or "og" occurs.

If anyone might have an idea about this I would greatly appreciate it.

Corey Sparks
Assistant Professor
Department of Demography and Organization Studies
University of Texas at San Antonio
One UTSA Circle
San Antonio, TX 78249
210 458 6858
corey.sparks at utsa.edu

More information about the R-help mailing list