23

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 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user1301593
  • 631
  • 1
  • 6
  • 16

2 Answers2

37

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)
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
  • 5
    In reading this answer again, I wonder if the OP only had the overall index because they ran `which` without `arr.ind=TRUE`. Future readers: if you're getting that index from `which`, use `arr.ind=TRUE` to get the row and column indices, instead of using `arrayInd`. – Aaron left Stack Overflow Nov 30 '12 at 20:35
9

Subsetting the matrix first results in a one-element vector that has no names, as you show in your question. Remember that subsetting creates a completely new object via copying. There's no way to reference the original mdat after subsetting.

This is more clear if you assign the result of subsetting to another object.

> m <- mdat[4]
> m
[1] 12
> names(m)  # no names were printed above... so
NULL

You really want to access the column/row names first and subset them.

> colnames(mdat)[3]
[1] "C.3"
> rownames(mdat)[2]
[1] "row2"

You can re-assign column/row names similarly.

> colnames(mdat)[3] <- "C3"
> rownames(mdat)[2] <- "row.2"
> mdat
      C.1 C.2 C3
row1    1   2  3
row.2  11  12 13
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418