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]
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.
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).
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.
colnames() function in R Language is used to set the names to columns of a matrix.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With