58

Is it possible to get a matrix column by name from a matrix?

I tried various approaches such as myMatrix["test", ] but nothing seems to work.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Suraj
  • 35,905
  • 47
  • 139
  • 250

2 Answers2

57

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Joris Meys
  • 106,551
  • 31
  • 221
  • 263
  • 10
    @Joris - you know, one of the tricky aspects of finding answers to R questions is that the language is named "R". It gives google a run for its money! I had googled searched my question above using a variety of search terms and came up with nothing. Its great when even simple questions are asked on SO, because SO is nicely indexed by google - results always seem to pop to the top. Hope other beginners find this =) – Suraj Apr 21 '11 at 13:38
  • 1
    @SFun28 : check www.rseek.org and eg this question : http://stackoverflow.com/questions/102056/how-to-search-for-r-materials But you're right, also simple questions can be asked here, although I would have simply sent you to Introduction to R if you were a new user. – Joris Meys Apr 21 '11 at 13:43
  • @Joris - sweet! rseek will be very useful. – Suraj Apr 21 '11 at 14:09
  • @Joris, You may have forgot to write, as.numeric( A[ ,"l"]) – Frank Dec 02 '16 at 18:42
  • @Frank which would be a wrong answer in case the values in that matrix are not numeric and shouldn't be converted to numeric. The question was to get the column, not to try to convert it to numeric. In case you wanted to use that trick to convert to a vector, you don't have to. If you select a single column or row, R automatically reduces the dimensions. You can avoid that using `drop = FALSE` as an extra argument to the index operator `[`, eg: `A[,'l', drop = FALSE]` – Joris Meys Dec 05 '16 at 16:21
32
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 
boraas
  • 929
  • 1
  • 10
  • 24