To get the column names of a matrix in R, you can use the colnames()
function. This function retrieves the column names as a vector.
In this example,
matrix1
using the matrix()
function with a vector of values c(1, 2, 3, 4)
and specify the number of rows as 2.c('Col1', 'Col2')
to the matrix using the colnames()
function.colnames()
function on matrix1
and store the result in a variable called colNames1
.print()
function to display the column names stored in colNames1
.matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
colnames(matrix1) <- c('Col1', 'Col2')
colNames1 <- colnames(matrix1)
print(colNames1)
[1] "Col1" "Col2"
In this example,
matrix2
using the matrix()
function with a vector of values c(1, 2, 3, 4, 5, 6, 7, 8, 9)
and specify the number of rows as 3.c('X', 'Y', 'Z')
to the matrix using the colnames()
function.colnames()
function on matrix2
and store the result in a variable called colNames2
.print()
function to display the column names stored in colNames2
.matrix2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
colnames(matrix2) <- c('X', 'Y', 'Z')
colNames2 <- colnames(matrix2)
print(colNames2)
[1] "X" "Y" "Z"
In this example,
matrix3
using the matrix()
function with a vector of values c(10, 20, 30, 40, 50, 60, 70, 80)
and specify the number of rows as 4.c('C1', 'C2')
to the matrix using the colnames()
function.colnames()
function on matrix3
and store the result in a variable called colNames3
.print()
function to display the column names stored in colNames3
.matrix3 <- matrix(c(10, 20, 30, 40, 50, 60, 70, 80), nrow = 4)
colnames(matrix3) <- c('C1', 'C2')
colNames3 <- colnames(matrix3)
print(colNames3)
[1] "C1" "C2"
In this tutorial, we learned How to get Column Names in a Matrix in R language with well detailed examples.