You make a matrix using matrix()rbind() or cbind() commands. The names of the rows and columns can be set after the matrix is produced in various ways:
- rownames() – sets the row names
- colnames() – sets the column names
- dimnames() – sets both row and column names in one command
The rownames() and colnames() commands set the row and column names respectively:
> m1 <- matrix(1:12, nrow = 3) > m1 [,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12 > rownames(m1) <- letters[26:24] > m1 [,1] [,2] [,3] [,4] z 1 4 7 10 y 2 5 8 11 x 3 6 9 12 > colnames(m1) <- LETTERS[26:23] > m1 Z Y X W z 1 4 7 10 y 2 5 8 11 x 3 6 9 12
The commands can also query the names:
> rownames(m1) [1] "z" "y" "x" > colnames(m1) [1] "Z" "Y" "X" "W"
Note that the basic names() command does not work for matrix objects:
> names(m1) NULL
If you use the rbind() command then the rows will be named according to the data names that you use unless you specify otherwise:
> d1 <- 1:4 ; d2 = 5:8 ; d3 = 9:12 > rbind(d1, d2, d3) [,1] [,2] [,3] [,4] d1 1 2 3 4 d2 5 6 7 8 d3 9 10 11 12 > rbind(Row1 = d1, Row2 = d2, Row3 = d3) [,1] [,2] [,3] [,4] Row1 1 2 3 4 Row2 5 6 7 8 Row3 9 10 11 12
Similarly with the cbind() command the columns take the names of the objects unless you specify them explicitly.
You can set the row and column names in one go using the dimnames() command. This requires a list() of two items (the row names and the column names):
> m1 Z Y X W z 1 4 7 10 y 2 5 8 11 x 3 6 9 12 > dimnames(m1) <- list(letters[1:3], LETTERS[1:4]) > m1 A B C D a 1 4 7 10 b 2 5 8 11 c 3 6 9 12
If you use the matrix() command you can incorporate the dimnames() command within it to set the names:
> m3 <- matrix(1:12, nrow = 3, dimnames = list(month.abb[1:3], month.abb[4:7]))
> m3
Apr May Jun Jul
Jan 1 4 7 10
Feb 2 5 8 11
Mar 3 6 9 12
Of course you can also use the dimnames() command to view the current names – more on this another time.