%in% operator

x %in% table
The %in% operator is used to check whether elements of x can be found in table, where each of these objects is commonly a single value or a vector.
  • x – A vector, or an object that can be coerced into a vector.
  • table – A vector, or an object that can be coerced into a vector.

Example. There are several examples below. Of particular interest, notice that NA does not return an NA result; rather, in these instances the %in% operator checks whether NA is found.
> set.seed(5)
> 
> 2 %in% 1:4
[1] TRUE
> 
> 2 %in% 3:6
[1] FALSE
> 
> (tab <- sample(10, 3))
[1] 3 7 8
> 
> 1:3 %in% tab
[1] FALSE FALSE  TRUE
> 
> c(1:3, NA) %in% tab
[1] FALSE FALSE  TRUE FALSE
> 
> c(1:3, NA) %in% c(tab, NA)
[1] FALSE FALSE  TRUE TRUE
> 
> "3" %in% tab
[1] TRUE
The set.seed function makes the code reproducible.

Leave a Reply