To assign row and column names to a matrix in R, you can use the rownames()
and colnames()
functions. These functions allow you to set or retrieve the row and column names of a matrix.
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.c('Col1', 'Col2')
to the matrix using the colnames()
function.print()
function to display the matrix with its row and column names.matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
rownames(matrix1) <- c('Row1', 'Row2')
colnames(matrix1) <- c('Col1', 'Col2')
print(matrix1)
Col1 Col2 Row1 1 3 Row2 2 4
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.c('X', 'Y', 'Z')
to the matrix using the colnames()
function.print()
function to display the matrix with its row and column names.matrix2 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3)
rownames(matrix2) <- c('A', 'B', 'C')
colnames(matrix2) <- c('X', 'Y', 'Z')
print(matrix2)
X Y Z A 1 4 7 B 2 5 8 C 3 6 9
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.c('C1', 'C2')
to the matrix using the colnames()
function.print()
function to display the matrix with its row and column names.matrix3 <- matrix(c(10, 20, 30, 40, 50, 60, 70, 80), nrow = 4)
rownames(matrix3) <- c('R1', 'R2', 'R3', 'R4')
colnames(matrix3) <- c('C1', 'C2')
print(matrix3)
C1 C2 R1 10 50 R2 20 60 R3 30 70 R4 40 80
In this tutorial, we learned How to Assign Row and Column Names in a Matrix in R language with well detailed examples.