What is the names() function in R?
Overview
We use the names() function in R to obtain or set the name of an R object.
Syntax
The syntax for the names() function is given below:
names(x)names(x) <- value
Syntax for the names() function in R
Parameters
The names() function takes the following parameter values:
x: This is an R object.value: This represents a character vector having the same length asx.
Example1
# creating an R objectmylist <- list(length = 10, height = 5, breadth = 2)# to obtain the names of the listnames(mylist)
Explanation
- Line 2: We use the
list()function to create an R object that ismylist. - Line 5: We use the
names()function to obtain the names of the object,mylist.
Example 2
# creating an R objecta <- 1:5# setting names to the objectnames(a) <- c("one", "two", "three", "four", "five")# to show the modified objecta
Explanation
- Line 2: We create an R object,
a. - Line 5: We set names to the R object using the
names()function. - Line 8: We print the object to the console.