1

Say I have a numerical vector in R. And I want to see if a particular integer is present in the vector or not. We can do that easily in python using 'in' command and an if statement may be.

Do we have something similar in R as well? So that I don't have to use a for loop to check if the integer I want is present in a vector? I tried the following, but it does not seem to work. 'normal' is a dataframe and the second column has integers.

if (12069692 in normal[,2]) {print("yes")}

Says,

Error: unexpected 'in' in "if (12069692 in"
Jordan
  • 311
  • 1
  • 4
  • 11
  • I'm sorry, but -1 for a lack of research effort. If I google *R find value in vector*, first hit is, I believe, a [duplicate of this question](http://stackoverflow.com/q/1169248/1478381) – Simon O'Hanlon Apr 11 '13 at 16:22

1 Answers1

5

In R, it's called %in%:

> 1 %in% c(1, 2, 3)
[1] TRUE
> 4 %in% c(1, 2, 3)
[1] FALSE

It is vectorized on the left-hand side, so you can check multiple values at once:

> c(1, 4, 2, 1) %in% c(1, 2, 3)
[1]  TRUE FALSE  TRUE  TRUE

(hat tip @Spacedman)

NPE
  • 486,780
  • 108
  • 951
  • 1,012