[R] Variable substitution in grep pattern

Thomas Lumley tlumley at u.washington.edu
Fri Jan 30 03:55:22 CET 2004


On Thu, 29 Jan 2004, Alberto Fornasier wrote:
>
> I've tried to use a "for" loop as follows:
>
> > for(i in Licenza.elenco) {
> + Licenza.elenco.prova[Licenza.elenco==i] <-
>   length(grep(".*i.*",as.character(Licenza)))}
>
> In which Licenza.elenco is a character vector containing all unique
> values I need to match (e.g. BSD License, Qt Public License (QPL), GNU
> General Public License (GPL)).
> However R handles as I expect only the first variable substitution (the
> index), but grep matches all strings containing the letter "i", that is
> 100% of the vector, except NAs of course.


You can't do that.  If you could , how would you search for all strings
containing the letter "i"?

You need to use something like paste() to construct the pattern

length(grep(paste(".*",i,".*",sep=""),as.character(Licenza)))}

	-thomas




More information about the R-help mailing list