[R] Testing for membership in an array of strings

Neil Tiffin neilt at neiltiffin.com
Thu Jul 2 16:13:15 CEST 2009


As an R beginner, I feel brain dead today as I can not find the answer  
to a relatively simple question.

Given a array of string values, for example lets say "mary", "bob",  
"danny", "sue", and "jane".

I am trying to determine how to perform a logical test to determine if  
a variable is an exact match for one of the string values in the array  
when the number of strings in the array is variable and without using  
a for loop and without comparing each value.  Considering the power of  
R, I thought this would be easy, but its not obvious to me.

Now I may not yet be one with the R fu so a bit more context.

I have a data frame that contains a column with text values. What I am  
trying to do is use the subset function on the data frame to select  
only data for "sue" or "jane" (for example.)  But maybe I have not  
taken the correct approach?

So obviously I could do something like the following.

subset( data_frame, name = "sue" | name == "jane", select = c(name,  
age, birthdate))

However, my subset needs to be much more than 2 and being lazy I do  
not want to type "| name == "some text" for each one.

Is there an other way?

Neil




More information about the R-help mailing list