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
2009-07-23 02:25:24
Why do you ask a question and then answer it yourself 3 minutes later? What's the point?...
Alex
2009-07-23 02:30:21
Have you heard of FlashMob??? http://blog.stackoverflow.com/2009/07/stack-overflow-flash-mobs/
jjnguy
2009-07-23 02:33:23
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
2009-07-23 02:34:13
wow, this is an awesome flash mob... i've seen three questions in the past half hour tagged <r>
geowa4
2009-07-23 02:44:32
Good idea, folks! (@jjnguy: no, I hadn't heard of it!!! :-))
ars
2009-07-23 03:13:18
using `%in%` makes the test extendible to set inclusion: `all(candidates %in% container)`.
mariotomo
2010-06-16 11:31:11
+3
A:
You can use the %in%
operator:
vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false
ars
2009-07-23 02:25:52
+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
2009-08-20 22:12:04