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

From: Allen S. Rout <asr_at_ufl.edu>
Date: Thu 27 Jul 2006 - 01:16:25 EST

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.


# 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?

R-help@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. Received on Thu Jul 27 01:24:48 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 27 Jul 2006 - 04:16:18 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.