59

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.

0

2 Answers 2

61

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)

Sign up to request clarification or add additional context in comments.

5 Comments

@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 =)
@SFun28 : check www.rseek.org and eg this question : stackoverflow.com/questions/102056/… 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 - sweet! rseek will be very useful.
@Joris, You may have forgot to write, as.numeric( A[ ,"l"])
@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]
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.