Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index value for matrix in R?

Is there a function to get an index (row number and column number) for a matrix?

Suppose that I have a simple matrix:

a <- matrix(1:50, nrow=5) 

Is there an easy way to get back something like c(3, 5) for the number "23", for instance? In this case, saying which(a==23) just returns 23.

This seems to work but I'm sure that there's a better way:

matrix.index <- function(a, value) {   idx <- which(data.frame(a)==value)   col.num <- ceiling(idx/nrow(a))   row.num <- idx - (col.num-1) * nrow(a)   return(c(row.num, col.num)) } > matrix.index(a, 23) [1] 3 5 > matrix.index(a, 50) [1]  5 10 
like image 267
Shane Avatar asked Dec 01 '09 22:12

Shane


People also ask

What is the index of a matrix?

Indexing into a matrix is a means of selecting a subset of elements from the matrix. MATLAB® has several indexing styles that are not only powerful and flexible, but also readable and expressive. Indexing is a key to the effectiveness of MATLAB at capturing matrix-oriented ideas in understandable computer programs.

Is R 1 or 0 index?

In R, array indexes start at 1 - the 1st element is at index 1. This is different than 0-based languages like C, Python, or Java where the first element is at index 0.

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

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.


1 Answers

Just looked at the help for which() after posting this and found the answer: the arr.ind parameter.

which(a==23, arr.ind=TRUE)      row col [1,]   3   5 
like image 144
Shane Avatar answered Sep 22 '22 07:09

Shane