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. IfFALSEand names areNULL, names are created.prefix: This represents the names that are created.value: This is a valid value for that component ofdimnames(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 eitherNULLor 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 objectscol1 <- c( 1 , 2 , 3 )col2 <- c("Lion", "Tiger", "Leopard")# conbining the matrix objectsc <- cbind(col1, col2)# setting the row and column namescolnames(c) <- c("Num", "Animal")rownames(c) <- c("row1", "row2", "row3")rownames(c) <- rownames(c, do.NULL=FALSE)# printing the matrixc# obtaining the column names of the matrixpaste(colnames(c))# obtaining the row names of the matrixpaste(rownames(c))
Code explanation
- Lines 2–3: We create the matrix objects
col1andcol2. - Line 6: We combine the matrix objects, using the
cbind()function. Then we assign the result to a variablec. - 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 variablec. - 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.