How to Use setNames Function in R (With Examples)


You can use the setNames function in R to set the names of an object and return the object.

This function uses the following basic syntax:

setNames(object, nm)

where:

  • names: The name of the object
  • nm: A character vector of names

The following examples show how to use this function in different scenarios.

Example 1: Use setNames with Vector

Suppose we create the following vector in R with names:

#create vector
data <- c(1, 3, 4, 4)

#create names for vector
names(data) <- c('points', 'rebounds', 'blocks', 'steals')

#view vector
data

  points rebounds   blocks   steals 
       1        3        4        4

We can create this exact same vector with names by just using the setNames() function:

#create vector with names
data <- setNames(c(1, 3, 4, 4), c('points', 'rebounds', 'blocks', 'steals'))

#view vector
data

  points rebounds   blocks   steals 
       1        3        4        4

By using just one line, we’re able to create the exact same vector with names.

Example 2: Use setNames with List

The following code shows how to use the setNames function to create a list with specific names in R and return the list:

#create list with names and return list
setNames(list(c(1, 2), 3:6, c('A', 'B')), c('points', 'steals', 'team'))

$points
[1] 1 2

$steals
[1] 3 4 5 6

$team
[1] "A" "B"

Notice that a list is returned with the names that we specified using the setNames function.

Also note that you can type the following into R to read the complete documentation for the setNames function:

?setNames

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Change Row Names in R
How to Loop Through Column Names in R
How to Use the names Function in R

Leave a Reply

Your email address will not be published.