Find Index Positions of Non-Zero Values in Matrix in R (Example)

 

This article explains how to get the indices of non-zero values in a matrix in the R programming language.

The article will contain the following information:

Let’s dive into it:

 

Example Data

The first step is to define some data that we can use in the examples later on:

my_mat <- matrix(c(0, 1, 2, 0, 0, 2, 1, 2, 0),    # Create example matrix
                 ncol = 3)
my_mat                                            # Print example matrix

 

table 1 matrix find index positions non zero values matrix r

 

As you can see based on Table 1, our example data is a matrix consisting of three rows and three numerical columns.

Some of the values in our matrix are equal to zero, others are unequal to zero.

 

Example: Identify Indices of Non-Zero Values in Matrix Using which() Function

The following syntax explains how to find the indices of all non-zero values in a matrix object.

For this task, we can apply the which. Within the which function, we have to set the arr.ind argument to be equal to TRUE:

mat_nonzero <- which(my_mat != 0, arr.ind = T)    # Identify non-zero values
mat_nonzero                                       # Print matrix of non-zero locations

 

table 2 matrix find index positions non zero values matrix r

 

By running the previous R syntax, we have managed to construct Table 2, i.e. a matrix showing the row and column indices of non-zero numbers.

For instance, there is a non-zero value in the second row in the first column.

 

Video, Further Resources & Summary

Have a look at the following video tutorial on my YouTube channel. I explain the R programming syntax of this tutorial in the video:

 

 

Furthermore, you may want to have a look at the related tutorials on this website.

 

Summary: This page has illustrated how to find the index locations of non-zero values in a matrix in the R programming language. Let me know in the comments section, in case you have any additional questions. Furthermore, please subscribe to my email newsletter in order to receive updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top