[R] integer(0) and NA do not equal FALSE

Stephan Kolassa Stephan.Kolassa at gmx.de
Sat Dec 19 21:59:08 CET 2009


Hi Jonathan,

grep() returns  a vector giving either the indices of the elements of 
'x' that yielded a match or, if 'value' is 'TRUE', the matched elements 
of 'x' (quoting from the help page, see ?grep).

So you probably want to test whether this vector is empty or not - in 
other words, whether it has length zero or not:

if( length(grep("hi", "hop", fixed = TRUE)) > 0 )
        print('yes, your substring is in your string') else
        print('no, your substring is not in your string')

(And you can remove the "fixed = TRUE" if you are only interested in 
whether the expression matches or not.)

One off-topic point: you want your "else" at the end of the second line, 
not the beginning of the third. R evaluates line by line, and when it 
gets to the end of the second line and doesn't see your "else", it has 
no way of knowing that the "if" is not yet finished. I've found that 
liberal use of curly braces makes life much easier.

HTH,
Stephan



Jonathan schrieb:
> Hi,
>    A noobie question:  I'm simply trying to run a conditional statement that
> evaluates if a substring is found within a larger string.  I find that if it
> IS found, my function returns TRUE (great!), but if not, the condition does
> not evaluate to FALSE.
> 
> ex):
> 
> if( grep("hi", "hop", fixed = TRUE) )
>       print('yes, your substring is in your string')
> else print('no, your substring is not in your string')
> 
> alternatively, I could replace grep with pmatch:
> 
> if (pmatch('hi','hop'))
>       print('yes, your substring is in your string')
> else print('no, your substring is not in your string')
> 
> 
> The first example, using grep, returns logical(0).  The second, using
> pmatch, returns NA.  Any idea how to convert either of those to FALSE, or
> else a different function that would do the trick?
> 
> Thanks,
> Jon
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.
>




More information about the R-help mailing list