What is the dimnames() function in R?

Overview

The dimnames() function in R is used to retrieve or set the dimnames of an object.

Syntax

dimnames(x)
dimnames(x) <- value
Syntax for the dimnames() function

Parameters

The dimnames() function takes the following parameter values:

  • x: An R object such as a matrix, array, or data frame.
  • value: A value to set the names of the object.

Code

Let's look at the code below:

# creating a matrix object
mymatrix <- matrix(c("apple",
"banana",
"cherry",
"mango",
"pineapple",
"lemon"), nrow = 3, ncol = 2)
# setting the name of rows and columns
dimnames(mymatrix) <- list( Rows = c('1', '2', '3'),
Cols = c('col1', 'col2'))
# printing the matrix object
mymatrix

Explanation

  • Lines 2 to 7: We create a matrix object, mymatrix with 3 rows and 2 columns using the matrix() function.
  • Lines 10 and 11: We use the dimnames() function to set the names of both the rows and columns of the matrix mymatrix.
  • Line 14: We print the matrix mymatrix.