How to check if an item exists in a matrix in R?

Overview

To understand what a matrix is and how to create a matrix in R, click here.

If we want to check whether an item exists in a given matrix or not, we use the %in% operator.

Example

# creating a matrix
mymatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
# to check if banana exists in the matrix
"banana" %in% mymatrix

Explanation

We create a 2x2 matrix (a matrix with 2 rows and 2 columns) mymatrix. Using the %in% operator, we check if the element "banana" exists in the matrix or not. The output of the code TRUE means that the element can be found in the given matrix.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources