Row & column names using dimnames() in R

The dimnames() command can set or query the row and column names of a matrix. Unlike rownames() or colnames() the dimnames() command operates on both rows and columns at once. If you use it to set the names you need to specify the names for the rows and columns in that order) in a list.

> m1 <- matrix(1:12, nrow = 3)
> dimnames(m1) <- list(month.abb[1:3], month.abb[4:7])
> m1
    Apr May Jun Jul
Jan   1   4   7  10
Feb   2   5   8  11
Mar   3   6   9  12

The dimnames() command retrieves the names like so:

> dimnames(m1)
[[1]]
[1] "Jan" "Feb" "Mar"

[[2]]
[1] "Apr" "May" "Jun" "Jul"

Notice the double square braces acting as element names. You can get one element by using the square brace notation:

> dimnames(m1)[1]
[[1]]
[1] "Jan" "Feb" "Mar"

> dimnames(m1)[[1]]
[1] "Jan" "Feb" "Mar"

When you use single braces you get the “name” of the element. If you use double braces you do not. The dimnames() command will work on matrix, array or data.frame objects.

You can use the command to set a single element but you need to use the double braces to get it to work:

> dimnames(m1)[[1]] <- letters[1:3]
m1
  Apr May Jun Jul
a   1   4   7  10
b   2   5   8  11
c   3   6   9  12

Note that you cannot set a single element to NULL although you can set all elements to NULL:

> dimnames(m1)[[1]] <- NULL
Error in dimnames(m1)[[1]] <- NULL :
length of 'dimnames' [1] not equal to array extent
> dimnames(m1) <- list(NULL, NULL)
> m1
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
Comments are closed.