Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]

like image 841
CodeKingPlusPlus Avatar asked Mar 08 '13 15:03

CodeKingPlusPlus


People also ask

How do you access the column of a matrix in R?

R – Get Specific Column of Matrix 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 you repeat a vector in a matrix in R?

The matrix can be created by using matrix function in R and if we want to create a matrix by replicating a vector then we just need to focus on the replication. For example, if we have a vector V and we want to create matrix by replicating V two times then the matrix can be created as matrix(replicate(2,V),nrow=2).

How do you slice a matrix in R?

Slice a Matrix We can select elements one or many elements from a matrix in R programming by using the square brackets [ ]. This is where slicing comes into the picture. For example: matrix_c[1,2] selects the element at the first row and second column.

How do you give column names to a matrix in R?

colnames() function in R Language is used to set the names to columns of a matrix.


2 Answers

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 
like image 54
NPE Avatar answered Nov 08 '22 14:11

NPE


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.

like image 44
ndoogan Avatar answered Nov 08 '22 14:11

ndoogan