Skip to content

vectorizing test for equality

2 messages · John Miyamoto, Brian Ripley

#
Dear R Help,
   I am trying to create a boolean vector that is TRUE whenever a
particular value occurs in a numeric vector, and FALSE otherwise.  For
example, suppose that
[1] 5 2 4 3 1

and suppose that I want to find where 3 occurs in y.  Then, the following
yields the solution:
[1] FALSE FALSE FALSE  TRUE FALSE

My problem arises when the numeric vector has missing values.  For
example, suppose that x is the vector
[1]  2 NA  1  5  3

Now x == 5 yields
[1] FALSE    NA FALSE  TRUE FALSE

whereas what I want is

FALSE  FALSE  FALSE  TRUE  FALSE

I can solve this problem with a for loop:
[1] FALSE FALSE FALSE  TRUE FALSE

Is there a way to avoid the for loop?  I'm also curious why the following
does not work, because it seems to me it should:
[1] FALSE FALSE FALSE FALSE FALSE

I was expecting to see FALSE FALSE FALSE TRUE FALSE.

John Miyamoto

--------------------------------------------------------------------
John Miyamoto, Dept. of Psychology, Box 351525
University of Washington, Seattle, WA 98195-1525
Phone 206-543-0805, Fax 206-685-3157, Email jmiyamot at u.washington.edu
Homepage http://faculty.washington.edu/jmiyamot/
--------------------------------------------------------------------
#
[1] FALSE FALSE FALSE  TRUE FALSE

Knowledge like this is covered in chapter 2 of MASS4 (Venables & Ripley,
2002).

Note that your subject is misleading:  == does test for equality, but that
is not what you actually wanted.
On Fri, 20 Dec 2002, John Miyamoto wrote: