Home » How to Use the names Function in R (3 Examples)

How to Use the names Function in R (3 Examples)

by Erma Khan

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

Related Posts