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 matrixmymatrix <- 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.