Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a matrix column and row name by a matrix index value?

So let's say I have a matrix, mdat and I only know the index number. How do I retrieve the column and row names? For example:

> mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol=3, byrow=TRUE, 
    dimnames = list(c("row1", "row2"), c("C.1", "C.2", "C.3"))) 
> mdat[4] 
[1] 12 
> names(mdat[4]) 
NULL 
> colnames(mdat[4]) 
NULL 
> rownames(mdat[4])
NULL 
> dimnames(mdat[4]) 
NULL 
like image 231
user1301593 Avatar asked Mar 29 '12 18:03

user1301593


1 Answers

First you need to get the row and column of that index using arrayInd.

k <- arrayInd(4, dim(mdat))

You can then get the right name by getting that element of the row and column names

rownames(mdat)[k[,1]]
colnames(mdat)[k[,2]]

Or both at once using mapply:

mapply(`[[`, dimnames(mdat), k)
like image 184
Aaron left Stack Overflow Avatar answered Oct 05 '22 20:10

Aaron left Stack Overflow