tags:

views:

3141

answers:

3

In R, how do you test a vector to see if it contains a given element?

+5  A: 

Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this.

v <- c('a','b','c','e')

'b' %in% v
## returns TRUE

match('b',v)
## returns 1
dataspora
Why do you ask a question and then answer it yourself 3 minutes later? What's the point?...
Alex
Have you heard of FlashMob??? http://blog.stackoverflow.com/2009/07/stack-overflow-flash-mobs/
jjnguy
match('b',v) should return the index of the first element in v that matches the string 'b'. In this case it would be 2.
Sharpie
wow, this is an awesome flash mob... i've seen three questions in the past half hour tagged <r>
geowa4
Good idea, folks! (@jjnguy: no, I hadn't heard of it!!! :-))
ars
using `%in%` makes the test extendible to set inclusion: `all(candidates %in% container)`.
mariotomo
+3  A: 

You can use the %in% operator:

vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false
ars
+2  A: 

The any() function makes for readable code

> w <- c(1,2,3)
> any(w==1)
[1] TRUE

> v <- c('a','b','c')
> any(v=='b')
[1] TRUE

> any(v=='f')
[1] FALSE
Dan Goldstein