23

In R I can access the data in a column vector of a column matrix by the following:

mat2[,1]

Each column of mat2 has a name. How can I retrieve the data from the first column by using the name attribute instead of [,1]?

For example suppose my first column had the name "saturn". I want something like

mat2[,1] == mat2[saturn]

1
  • Read the documentation, e.g. ?"[", or any introduction to R. Commented Mar 8, 2013 at 16:34

2 Answers 2

25

The following should do it:

mat2[,'saturn']

For example:

> x <- matrix(1:21, nrow=7, ncol=3)
> colnames(x) <- paste('name', 1:3)
> x[,'name 1']
[1] 1 2 3 4 5 6 7
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'm a beginner in R. also just to add that column name is case-sensitive.
Just to add it can also be done like mat2$saturn
@SaqibMustafaAbbasi in R, matrices are atomic, not recursive objects. If you try to use $ on a matrix, you should get this error: stackoverflow.com/questions/23299684/…
14

Bonus information (adding to the first answer)

x[,c('name 1','name 2')]

would return two columns just as if you had done

x[,1:2]

And finally, the same operations can be used to subset rows

x[1:2,]

And if rows were named...

x[c('row 1','row 2'),]

Note the position of the comma within the brackets and with respect to the indices.

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.