a shot of dev knowledge


How to check if an array item is present in R


An array in R is a data structure that can hold multi-dimensional data of the same data type.

Using the %in% operator

We can check the presence of an element in an array using the %in% operator. This operator returns a Boolean value of TRUE or FALSE, depending on the computation results.


In the following example, we create an array of integers ranging from 1 to 10. Then, we use the %in% operator to check for the presence of 5 in the array.

# creating an array variable
myarray <- c(1:10)

# creating a multidimensional array using the array() function
multiarray <- array(myarray, dim = c(3,2))

# to check if 5 is present in the array using %in% operator
5 %in% myarray 
Checking for the existence of an item using the %in% operator

Code explanation

  • Line 2: We create an array, myarray, with elements ranging from 1 to 10.
  • Line 5: We use the array() function to create a 3 by 2 dimensional array.
  • Line 9: We use the %in% operator to check if the item 5 is present in the array.



View all Courses

Keep Exploring