# [R] Branching on 'grep' returns...

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jul 26 17:31:43 CEST 2006

```If you are using grep then I think you have it right.  Note that

"this" %in% trg

is also available.

On 26 Jul 2006 11:16:25 -0400, Allen S. Rout <asr at ufl.edu> wrote:
>
>
>
> Greetings, all.
>
> I'm fiddling with some text manipulation in R, and I've found
> something which feels counterintuitive to my PERL-trained senses; I'm
> hoping that I can glean new R intuition about the situation.
>
> Here's an example, as concise as I could make it.
>
>
> trg<-c("this","that")
>
> # these two work as I'd expected.
> if ( grep("this",trg) ) { cat("Y\n") } else { cat("N\n") }
> if ( grep("that",trg) ) { cat("Y\n") } else { cat("N\n") }
>
> # These all fail with error 'argument is of length zero'
> # if ( grep("other",trg) ) { cat("Y\n") } else { cat("N\n") }
> # if ( grep("other",trg) == TRUE) { cat("Y\n") } else { cat("N\n") }
> # if ( grep("other",trg) == 1) { cat("Y\n") } else { cat("N\n") }
>
>
> # This says that the result is a numeric zero.   Shouldn't I be able
> #  to "if" on that, or at least compare it with a number?
> grep("other", trg)
>
> # I eventually decided this worked, but felt odd to me.
> if ( any(grep("other",trg))) { cat("Y\n") } else { cat("N\n") }
>
>
> So, is the 'Wrap it in an any()' just normal R practice, and I'm too
> new to know it?  Is there a more fundamental dumb move I'm making?
>
>
>
>
> - Allen S. Rout
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>

```

More information about the R-help mailing list