r matrix rownames code example
Example 1: how to create a matrix with row and column names in r
> x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))
> x
A B C
X 1 4 7
Y 2 5 8
Z 3 6 9
> colnames(x)
[1] "A" "B" "C"
> rownames(x)
[1] "X" "Y" "Z"
> # It is also possible to change names
> colnames(x) <- c("C1","C2","C3")
> rownames(x) <- c("R1","R2","R3")
> x
C1 C2 C3
R1 1 4 7
R2 2 5 8
R3 3 6 9
Example 2: get matrix row name r
> grades_matrix
Math Science Art
Student_1 90 88 75
Student_2 78 81 95
Student_3 84 85 83
> rownames(grade_matrix)[2]
[1] "Student_2"
> colnames(grade_matrix)[3]
[1] "Art"