Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract matrix column values by matrix column name

Tags:

r

matrix

subset

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.

like image 347
SFun28 Avatar asked Apr 21 '11 13:04

SFun28


People also ask

How do you extract a column of a matrix in R?

To get a specific column of a matrix, specify the column number preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.

How do I get the column names of a matrix in R?

Row & column names using dimnames() in RThe dimnames() command can set or query the row and column names of a matrix. Unlike rownames() or colnames() the dimnames() command operates on both rows and columns at once.


1 Answers

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)

like image 184
Joris Meys Avatar answered Oct 21 '22 18:10

Joris Meys