To get the row names of a matrix in R, you can use the rownames()
function. This function retrieves the row 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('Row1', 'Row2')
to the matrix using the rownames()
function.rownames()
function on matrix1
and store the result in a variable called rowNames1
.print()
function to display the row names stored in rowNames1
.matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
rownames(matrix1) <- c('Row1', 'Row2')
rowNames1 <- rownames(matrix1)
print(rowNames1)
[1] "Row1" "Row2"
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('A', 'B', 'C')
to the matrix using the rownames()
function.rownames()
function on matrix2
and store the result in a variable called rowNames2
.print()
function to display the row names stored in rowNames2
.matrix2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
rownames(matrix2) <- c('A', 'B', 'C')
rowNames2 <- rownames(matrix2)
print(rowNames2)
[1] "A" "B" "C"
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('R1', 'R2', 'R3', 'R4')
to the matrix using the rownames()
function.rownames()
function on matrix3
and store the result in a variable called rowNames3
.print()
function to display the row names stored in rowNames3
.matrix3 <- matrix(c(10, 20, 30, 40, 50, 60, 70, 80), nrow = 4)
rownames(matrix3) <- c('R1', 'R2', 'R3', 'R4')
rowNames3 <- rownames(matrix3)
print(rowNames3)
[1] "R1" "R2" "R3" "R4"
In this tutorial, we learned How to get Row Names in a Matrix in R language with well detailed examples.