6.2 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Use setNames Function in R (With Examples)

How to Use setNames Function in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 #create names for vector
names(data) #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 #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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories