R Using which() Function to Get Matrix Index of Value (Example Code)

In this R tutorial you’ll learn how to find the index positions of certain elements in a matrix using the which() function.

Creation of Example Data

my_data <- matrix(letters[1:6], ncol = 6, nrow = 4)  # Constructing matrix in R
my_data                                              # Display example matrix in RStudio
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] "a"  "e"  "c"  "a"  "e"  "c" 
# [2,] "b"  "f"  "d"  "b"  "f"  "d" 
# [3,] "c"  "a"  "e"  "c"  "a"  "e" 
# [4,] "d"  "b"  "f"  "d"  "b"  "f"

Example: Get Row & Column Index Positions of Particular Value in Matrix

which(my_data == "a", arr.ind = TRUE)                # Return position matrix
#      row col
# [1,]   1   1
# [2,]   3   2
# [3,]   1   4
# [4,]   3   5

Further Resources

In the following, you can find some additional resources on topics such as data inspection, vectors, indices, and variables.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top