Get Index Locations of Non-Zero Values in Matrix in R (Example Code)
In this tutorial you’ll learn how to find the index locations of non-zero values in a matrix in the R programming language.
Example Data
set.seed(2375978) x <- matrix(sample(0:3, 12, replace = TRUE), # Example matrix in R ncol = 4) x # Display example matrix in RStudio console # [,1] [,2] [,3] [,4] # [1,] 3 0 2 0 # [2,] 3 3 3 2 # [3,] 0 1 3 3 |
set.seed(2375978) x <- matrix(sample(0:3, 12, replace = TRUE), # Example matrix in R ncol = 4) x # Display example matrix in RStudio console # [,1] [,2] [,3] [,4] # [1,] 3 0 2 0 # [2,] 3 3 3 2 # [3,] 0 1 3 3
Example: How to Find Index Positions of Non-Zero Values in Matrix
x_nonz <- which(x != 0, arr.ind = T) # Find non-zero cells x_nonz # Matrix with non-zero locations # row col # [1,] 1 1 # [2,] 2 1 # [3,] 2 2 # [4,] 3 2 # [5,] 1 3 # [6,] 2 3 # [7,] 3 3 # [8,] 2 4 # [9,] 3 4 |
x_nonz <- which(x != 0, arr.ind = T) # Find non-zero cells x_nonz # Matrix with non-zero locations # row col # [1,] 1 1 # [2,] 2 1 # [3,] 2 2 # [4,] 3 2 # [5,] 1 3 # [6,] 2 3 # [7,] 3 3 # [8,] 2 4 # [9,] 3 4
Related Tutorials
In the following, you can find some additional resources on topics such as data inspection, missing data, matrices, and extracting data: