17.6 C
London
Tuesday, July 22, 2025
HomeStatistics TutorialRHow to Use the names Function in R (3 Examples)

How to Use the names Function in R (3 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 names() function to set the names of an object or get the names of an object in R.

This function uses the following syntax:

#get names of object
names(x)

#set names of object
names(x) 

The following examples show how to use the names() function with different objects.

Example 1: Use names() Function with Vector

We can use the names() function to set the names for a vector:

#create vector
my_vector #view vector
my_vector

[1]  5 10 15 20 25

#set names for vector
names(my_vector) A', 'B', 'C', 'D', 'E')

#view updated vector
my_vector

 A  B  C  D  E 
 5 10 15 20 25 

We can then use brackets to access the values in a vector based off the name:

#access value in vector that corresponds to 'B' name
my_vector['B']

 B 
10

Example 2: Use names() Function with List

We can use the names() function to set the names for a list:

#create list
my_list #view list
my_list

[[1]]
[1] 1 2 3

[[2]]
[1] "hello"

[[3]]
[1] 10

#set names for list
names(my_list) A', 'B', 'C')

#view updated list
my_list

$A
[1] 1 2 3

$B
[1] "hello"

$C
[1] 10

We can then use brackets to access the values in a list based off the name:

#access value in list that corresponds to 'C' name
my_list['C']

$C
[1] 10

Example 3: Use names() Function with Data Frame

We can use the names() function to set the names for the columns of a data frame:

#create data frame
df frame(A=c('A', 'B', 'C', 'D', 'E'),
                 B=c(99, 90, 86, 88, 95),
                 C=c(33, 28, 31, 39, 34),
                 D=c(30, 28, 24, 24, 28))	

#get names of data frame
names(df)

[1] "A" "B" "C" "D"

#set names of data frame
names(df) team', 'points', 'assists', 'rebounds')

#view updated names of data  frame
names(df)

[1] "team"     "points"   "assists"  "rebounds"

Additional Resources

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

How to Add a Column to a Data Frame in R
How to Add an Empty Column to a Data Frame in R
How to Sort a Data Frame by Column 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