R, accessing a column vector of a matrix by name [duplicate]

南楼画角 提交于 2019-12-19 05:08:26

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/15297746/r-accessing-a-column-vector-of-a-matrix-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!