Not in R: How to Use R %notin% Operator with Example

An operator is a symbol that tells the compiler to execute particular logical or mathematical computations.

R language comes with binary and logical operators that make programmers’ life easy. Please note that binary operators operate on vectors and matrices as well as scalars. Let’s see more about not in operator in this article.

The not-in operator is a logical vector, negating the %in% operators on the same arguments.

Not in R

The not in r is the Negation of the %in%  operator.  The %in% operator is used to identify if an element belongs to a vector. The ! indicates logical negation (NOT).

A “NOT IN” operator that is cognitively simpler than the more verbose! x %in% table. See the following syntax of %!in%.

Please note that the NOT IN(%!in%) is not an inbuilt operator like the %in% operator, but we can define it using the Negate operator. We will see in this article that how we can define the %!in% operator and use it in the example.

Syntax

x %!in% table

Parameters

x

The values to be matched.

table

The values to not be matched against.

Example of not in operator in R

Let’s define two vectors called v1 and v2.

v1 <- 4
v2 <- 11

Now, we define the sequence of 1: 10.

s <- 1:10

Now, we will check the vector values against this sequence and include them in the sequence using in operator.

v1 <- 4
v2 <- 11
s <- 1:10
print(v1 %in% s)
print(v2 %in% s)

Output

[1] TRUE
[1] FALSE

You can see that 4 is in the sequence, so the %in% operator returns TRUE. 11 is not in the sequence, so it returns FALSE.

Now, let’s use the %!in% operator, but the problem with this is that there is not inbuilt %!in% operator in R.

If you use the %!in% operator in R, you will face the following error.

could not find function “%!in%” in r

To resolve this issue, we need to define the %!in% operator. Write the following code to define the Negate %in% operator.

`%!in%` <- Negate(`%in%`)

Now, you can use the %!in% operator.

v1 <- 4
v2 <- 11
t <- 1:10

`%!in%` <- Negate(`%in%`)
print(v1 %!in% t)
print(v2 %!in% t)

Output

[1] FALSE
[1] TRUE

You can see that v1 is included in 1: 10 but not in operator negates this. That is why it returns FALSE.

In the second example, 11 is not included, 1:10, which means negates condition returns TRUE, and it returns TRUE.

That is it for Not in operator in R example.

See also

OR operator in R

Operators in R

Leave a Comment