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

Thomas Lumley tlumley at u.washington.edu
Wed Jul 26 18:21:23 CEST 2006

```On Wed, 26 Jul 2006, Allen S. Rout wrote:
> # 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)

It is a numeric(0), that is, a zero-length vector of numbers. If you
compare it with a number you get a zero-length logical vector. You can't
get TRUE or FALSE, because a zero-length vector of 1s looks just like a
zero-length vector of 0s, (or a zero-length vector of any other number)

In handling zero-length vectors (and in other vectorization contexts) it
is useful to distinguish between vectorized functions, which return a
vector of the same length as the input, and reducing functions, which
return a vector of length 1.

The == operator is vectorized, but if() requires a condition of length 1,
so they don't match.  The solution is to apply some reducing function.
Two possible options are length() and (as you found) any().

-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

```