user2005253
user2005253

Reputation:

Fast way to figure out if a number is inside a vector in R

I was hoping to figure out a fast way to find out if a number is contained within a vector for the purpose of passing it to an if statement. So far, the best I have come up with is the following:

a = 5
b = 1:10

if(length(which(a==5)) > 0){

#Do something...

}

I'm sure there is a faster way of doing this.

Upvotes: 2

Views: 94

Answers (2)

hadley
hadley

Reputation: 103898

The fastest way is to use any(a == b):

library(microbenchmark)
options(digits = 3)

a <- 5
b <- 1:10

microbenchmark(
  length(which(a == b)) > 0, 
  a %in% b,
  any(a == b)
)
# Unit: nanoseconds
#                       expr  min   lq median   uq  max neval
#  length(which(a == b)) > 0 1328 1414   1472 1587 5765   100
#                   a %in% b 1519 1690   1773 1864 6665   100
#                any(a == b)  662  728    786  844 6205   100

But I'd agree that a %in% b is more clear, and it's unlikely saving 1 µs will have a noticeable impact on your code.

Also note that any of these methods will only work for characters and integers, not floating point numbers, and only when a is a scalar.

Upvotes: 2

Hong Ooi
Hong Ooi

Reputation: 57686

Use %in%:

if (a %in% b) ...

This may not necessarily be faster than what you've got (since it's just syntactic sugar for a match call) but it's certainly more compact and transparent.

Upvotes: 3

Related Questions