[R] what is returned if a match is not found using grep

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 11 13:04:53 CEST 2009


Rnewbie wrote:
> dear all,
>
> I tried to use grep to match IDs in two dataframes
>
> grep(DF1$ID[i], DF2$ID)
>
> I wanted to use condition in a loop, but I have the problem to define what
> is in return if a match is not found. I used mode() and class() to compare
> between the attributes when a match is found and not found, but the mode and
> class are the same in both cases, numeric and integer, respectively.
>
> When a match is not found, grep returns "integer(0)". Is.numeric() and
> Is.integer() of the return gave TRUE but arithmetic calculation is not
> possible.
>   
See the Value section of the ?grep man page.  By default, R returns a 
vector of indices of entries in x that match the pattern.  Since you 
have no matches, you get a vector of length 0.  That is printed as 
integer(0).  (This is also the function call that would create a vector 
of length 0.)

One simple test for no results is  length(grep(...)) == 0.

Duncan Murdoch
> For example,
> If a match is not found for i=12,
>
> grep(DF1$ID[12], DF2$ID) returns "integer(0)" and 
>
> grep(DF1$ID[12], DF2$ID)+10 returns "numeric(0)"
>
> I will appreciate any suggestions. Thanks in advance.
>
>
>




More information about the R-help mailing list