What are the rownames() and colnames() functions in R?

Overview

The rownames() and colnames() functions in R are used to obtain or set the names of the row and column of a matrix-like object, respectively.

Syntax

rownames(x, do.NULL = TRUE, prefix = "row")
rownames(x) <- value
colnames(x, do.NULL = TRUE, prefix = "col")
colnames(x) <- value

Parameter values

The rownames() and colnames() functions take the following parameter values:

  • x: This is a matrix-like object that has at least two dimensions.
  • do.Null: This takes a logical value. If FALSE and names are NULL, names are created.
  • prefix: This represents the names that are created.
  • value: This is a valid value for that component of dimnames(x) (that is, the values must be of the same dimension as the dimension of the matrix-like object). For a given array or matrix, this is either NULL or a character vector of non-zero length equal to the appropriate dimension.

Return value

The rownames() and colnames() functions both return a matrix object.

Code example

# creating the matrix objects
col1 <- c( 1 , 2 , 3 )
col2 <- c("Lion", "Tiger", "Leopard")
# conbining the matrix objects
c <- cbind(col1, col2)
# setting the row and column names
colnames(c) <- c("Num", "Animal")
rownames(c) <- c("row1", "row2", "row3")
rownames(c) <- rownames(c, do.NULL=FALSE)
# printing the matrix
c
# obtaining the column names of the matrix
paste(colnames(c))
# obtaining the row names of the matrix
paste(rownames(c))

Code explanation

  • Lines 2–3: We create the matrix objects col1 and col2.
  • Line 6: We combine the matrix objects, using the cbind() function. Then we assign the result to a variable c.
  • Line 10: We set names for the columns, using the colnames() function.
  • Line 11: We set names for the rows, using the rownames() function.
  • Line 13: We call the rownames() function on the variable c.
  • Line 16: We print the variable c.
  • Line 18: We obtain and print the column names of the matrix object, using the colnames() function.
  • Line 22: We obtain and print the row names of the matrix object, using the colnames() function.

Free Resources