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

Allen S. Rout asr at ufl.edu
Wed Jul 26 17:16:25 CEST 2006




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



More information about the R-help mailing list