Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matrix
r
communitycreator

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

Onyejiaku Theophilus Chidalu

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
Checking for the existence of an element using the %in% operator

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.

RELATED TAGS

matrix
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring