[R] vectorizing test for equality
John Miyamoto
jmiyamot at u.washington.edu
Fri Dec 20 09:17:03 CET 2002
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
> y <- c(5, 2, 4, 3, 1)
> y
[1] 5 2 4 3 1
and suppose that I want to find where 3 occurs in y. Then, the following
yields the solution:
> y == 3
[1] FALSE FALSE FALSE TRUE FALSE
My problem arises when the numeric vector has missing values. For
example, suppose that x is the vector
> x <- c( 2, NA, 1, 5, 3)
> x
[1] 2 NA 1 5 3
Now x == 5 yields
> x == 5
[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:
> flag <- NULL
> for (i in 1:length(x)) flag <- c(flag, identical(x[i], 5))
> flag
[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:
> test <- function(x) identical(x[1], x[2])
> apply(cbind(x, 5), 1, test)
[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/
--------------------------------------------------------------------
More information about the R-help
mailing list