Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - return position of element in matrix?

Tags:

Given a matrix:

      [,1] [,2] [1,]    0  0.0 [2,]   -1  0.8 

What is the quickest way in R to iterate over the matrix and return the position of all non-zero entries as an index?

like image 572
Darren J. Fitzpatrick Avatar asked Jun 29 '11 14:06

Darren J. Fitzpatrick


People also ask

How do you find the position of an element in a matrix?

The position of a matrix is the row number followed by the column number where that element is present. For example, in the matrix B = [131−10232] [ 1 3 1 − 1 0 2 3 2 ] , 1 is present in the 1st row and the 3rd column and hence we can write B₁, ₃ = 1 (or) B₁₃ = 1.

How do I find the position of an element in R?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.

How do I extract elements from a vector in R?

Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.

What is matrix () in R?

A matrix function in R is a 2-dimensional array that has m number of rows and n number of columns. In other words, matrix in R programming is a combination of two or more vectors with the same data type. Note: It is possible to create more than two dimensions arrays with matrix function in R.


2 Answers

Here is one approach

mat = matrix(rnorm(9), 3, 3) which(mat !=0, arr.ind = T) 
like image 99
Ramnath Avatar answered Oct 18 '22 20:10

Ramnath


m <- matrix(c(0, 1, 1, 0), nrow = 2) which(m != 0) 

or maybe

which(m != 0, TRUE) 
like image 22
Richie Cotton Avatar answered Oct 18 '22 19:10

Richie Cotton