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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to