Skip to content
Prev 33174 / 398506 Next

Multiple match function?

At Wednesday 03:28 AM 6/11/2003 +0200, Jonck van der Kogel wrote:
Actually, there are different ways of using match().  I think the following 
does what you want:

 > x <- c(1,1,2,2,3,3,4,4)
 > # how you were using it
 > match(2, x)
[1] 3
 > # switch the arguments around to get a non-NA value for each position of 
x that matches at least one element of a set
 > match(x, 2)
[1] NA NA  1  1 NA NA NA NA
 > # see which elements of x are in the set {2}
 > which(!is.na(match(x, 2)))
[1] 3 4
 > # see which elements of x are in the set {3}
 > which(!is.na(match(x, 3)))
[1] 5 6
 > # see which elements of x are in the set {2,3}
 > which(!is.na(match(x, c(2,3))))
[1] 3 4 5 6
 >

The operator %in% provides a more intuitive interface for this usage of 
match().
As others have already pointed out, which() together with "==" may be all 
you need.