[R] return value for grep

David Winsemius dwinsemius at comcast.net
Sun Oct 31 05:23:35 CET 2010


On Oct 30, 2010, at 11:13 PM, David Winsemius wrote:

>
> On Oct 30, 2010, at 10:51 PM, Ulrich wrote:
>
>> Hi,
>>
>> is it possible to easily change the return value for the grep  
>> function for cases where there is no match, for example the value 0  
>> or "No" instead of integer (0) )?
>>
>
> Seems like is should be  pretty easy. Test for length(grep(...)) ==  
> 0 or equivalently !length(grep(...))
>
> > gvec <- function(patt, x) sapply (x, function(y) if ( ! 
> length(grep(patt, y)) ) {"No"} else {grep(patt, y)} )
> > gvec("b", c("abc", "abc\n"))
>  abc abc\n
>    1     1
> > gvec("\n", c("abc", "abc\n"))
>  abc abc\n
> "No"   "1"
>

It later occurred to me that you might only want the alternate  
behavior when no matches were present:

gvec2 <- function(patt, x) if ( !length(grep(patt, y)) ) {0} else  
{grep(patt, y)}

 > gvec2 <- function(patt, x) if ( length(grep(patt, x))==0 ) {0} else  
{grep(patt, x)}
 > grep("\n", c("abc", "abc\n"))
[1] 2
 > gvec2("\n", c("abc", "abc"))
[1] 0


> -- 
>
> David Winsemius, MD
> West Hartford, CT



More information about the R-help mailing list