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
# creating a matrix objectmymatrix <- matrix(c("apple","banana","cherry","mango","pineapple","lemon"), nrow = 3, ncol = 2)# setting the name of rows and columnsdimnames(mymatrix) <- list( Rows = c('1', '2', '3'),Cols = c('col1', 'col2'))# printing the matrix objectmymatrix
Explanation
- Lines 2 to 7: We create a matrix object,
mymatrixwith 3 rows and 2 columns using thematrix()function. - Lines 10 and 11: We use the
dimnames()function to set the names of both the rows and columns of the matrixmymatrix.
- Line 14: We print the matrix
mymatrix.