[R] About grep

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Tue Aug 7 08:43:28 CEST 2007


On 07-Aug-07 04:20:27, Shao wrote:
> Hi,everyone.
> 
> I have a problem when using the grep.
> for example:
> a <- c("aa","aba","abac")
> b<- c("ab","aba")
> 
> I want to match the whole word,so
> grep("^aba$",a)
> it returns 2
> 
> but when I used it a more useful way:
> grep("^b[2]$",a),
> it doesn't work at all, it can't find it, returning integer(0).
> 
> How can I chang the format in the second way?
> 
> Thanks.
> 
> -- 
> Shao

The problem is that in the string "^b[2]$" the element b[2] of b
is not evaluated, but simply the successive characters ^ b [ 2 ] $
are passed to grep as a character string, which of course is not
found. You can construct a character string with the value of b[2]
in it by using paste():

grep(paste("^",b[2],"$",sep=""),a)
[1] 2

Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-Aug-07                                       Time: 07:43:14
------------------------------ XFMail ------------------------------



More information about the R-help mailing list