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) )? Thanks, Uli
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" -- David Winsemius, MD West Hartford, CT
On Sat, Oct 30, 2010 at 10:51 PM, Ulrich <ulrich.schlecht at stanford.edu> 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) )? >Try this:> Find(length, list(grep("X", letters), 0))[1] 0> Find(length, list(grep("X", LETTERS), 0))[1] 24 -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com
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
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) )?It sounds like you might want grepl (which returns a vector of TRUE and FALSE values) rather than grep (which returns a vector of indices or matches). Duncan Murdoch