4

How can one determine the row index-numbers corresponding to particular row names? I have a vector of row names, and I would like to use these to obtain a vector of the corresponding row indices in a matrix.

I tried row() and as.integer(rownames(matrix.object)), but neither seems to work.

starball
  • 20,030
  • 7
  • 43
  • 238
Roger
  • 677
  • 2
  • 8
  • 19

2 Answers2

11

In addition to which, you can look at match:

m <- matrix(1:25, ncol = 5, dimnames = list(letters[1:5], LETTERS[1:5]))
vec <- c("e", "a", "c")
match(vec, rownames(m))
# [1] 5 1 3
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
3

Try which:

which(rownames(matrix.object) %in% c("foo", "bar"))
sgibb
  • 25,396
  • 3
  • 68
  • 74
  • 1
    You'll get the same answer if you use `c("foo", "bar")` or `c("bar", "foo")`. I really think `match` is the correct answer, assuming row names are unique. – flodel Dec 18 '13 at 17:27
  • @flodel: You are right. My answer doesn't preserve the order of the names. – sgibb Dec 18 '13 at 17:42