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 as x.

Example1

# creating an R object
mylist <- list(length = 10, height = 5, breadth = 2)
# to obtain the names of the list
names(mylist)

Explanation

  • Line 2: We use the list() function to create an R object that is mylist.
  • Line 5: We use the names() function to obtain the names of the object, mylist.

Example 2

# creating an R object
a <- 1:5
# setting names to the object
names(a) <- c("one", "two", "three", "four", "five")
# to show the modified object
a

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.