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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With