R Tutorial R Charts & Graphs R Statistics R References

R - Matching operator



In R, the Matching operator %in% is used to check the presence of an element in a given vector (or matrix) and returns boolean value.

Example: Check the presence of a scalar (single element atomic vector)

Consider the example below, where ! operators is used with a vector.

x1 <- 10
v1 <- c(10, 20, 30, 40)
m1 <- matrix(c(100, 200, 300, 400), nrow=2)

#checking x1 in v1
print(x1 %in% v1)
#checking x1 in m1
print(x1 %in% m1)

The output of the above code will be:

[1] TRUE
[1] FALSE

Example: Check the presence of a sequence

When a sequence is checked then it takes each element of the sequence one by one and tests its presence in the given vector (or matrix). Consider the example below:

v1 <- c(10, 20, 30, 40)
v2 <- c(10, 15, 20)

#checking (10:15) in v1
print((10:15) %in% v1)
#checking v2 in v1
print(v2 %in% v1)

The output of the above code will be:

[1]  TRUE FALSE FALSE FALSE FALSE FALSE
[1]  TRUE FALSE  TRUE

❮ R - Operators