0

I have the following matrix:

m = matrix( c("l","K","p","j",
              "f","n","n","i",
              "l","n","n","c",
              "a","g","r","s"),nrow=4,byrow=TRUE )

I know that m[2,3] equals "n" . How can I get the corresponding index number? By that I mean, how can I get the index that will give me the value of the matrix at that position (2nd row, 3rd column). In this case it would be 10, because m[10] will give me back the "n" at the position in the 2nd row and the 3rd column. I would be glad if the solution would work also for the case that I have only the row and column name(if rows and columns have been named) that identify a certain position in the matrix.

Alias
  • 149
  • 1
  • 9
  • `matrix(seq_along(m), nrow = nrow(m))[2,3]` – alistaire Jul 24 '16 at 16:29
  • Zheyuan Li, yes that solves it, thanks. I just had to figure out how to convert the row and col names to the actual row and column numbers to make use of that solution. For the conversion to the actual row and column numbers that post was helpful: http://stackoverflow.com/questions/20663720/how-to-get-row-index-number-for-particular-names – Alias Jul 24 '16 at 16:34
  • or with dimnames, `matrix(seq_along(m), nrow = nrow(m), dimnames = dimnames(m))[2,3]` – alistaire Jul 24 '16 at 16:38
  • I think the answer should be to find a duplicate illustrating the use of `which`. Either `which(m=="n")` for the 10 result or `which(m=="n", arr.ind=TRUE)` for the c(2,3) result. – IRTFM Jul 24 '16 at 18:39
  • I will note that the request for the case when the row and column names are known is a bit strange since the R `[` function will accept those for indexing. – IRTFM Jul 24 '16 at 18:53

0 Answers0