[R] grep on vectors?

Allan Engelhardt allane at cybaea.com
Wed Jul 1 12:41:11 CEST 2009


On 30/06/09 17:53, Chuck White wrote:
> [...]
>
> Is there a way to avoid the for loop? The following seems to work:
>    lapply(density.factor,grep,names(data.df))
> However, that produces a list of lists which need to be merged. Note that in the above example since we have 2 regular expressions, there will be two lists but in the general case there will be many more.
It is hiding, not avoiding the for loop, but if you are happy with the 
lapply() approach then just use unlist() on the result:

unlist(lapply(density.factor, grep, names(data.df)))

I wouldn’t worry about optimizing performance: it isn’t the sort of 
thing you are going to be running a million times per second.  Keep it 
understandable and maintainable.

Hope this helps a little.

Allan.




More information about the R-help mailing list