The names() function in R gets or sets the names of objects such as vectors, lists, or data frames. If you are using it to fetch the name, it will return a character vector containing the names assigned to its elements or columns.
Syntax
names(obj) # To get names
names(obj) <- value # To set names
Parameters
Name | Value |
obj | It is an input object whose name you want to set or get. |
value | It is a character vector of the same length as the input object. |
Vectors
Let’s declare a vector and try to get its name.
vec_obj <- c(11, 21, 19, 18)
names(vec_obj) # Output: NULL
You can see that since we did not assign any name to it, by default, it is NULL.
Let’s set the name of the vector and get it:
vec_obj <- c(11, 21, 19, 18)
names(vec_obj) # Output: NULL
names(vec_obj) <- c("a", "b", "c", "d")
names(vec_obj) # Output: [1] "a" "b" "c" "d"
Here, we set the name using the name(obj) <- value syntax where obj is our vec_obj and value is our new character vector.
You can also analyze that the length of vec_obj is the same as the character_vector (name) we assigned to the object.
Now, you can access the individual elements of a vector by their names.
vec_obj <- c(11, 21, 19, 18)
names(vec_obj) <- c("a", "b", "c", "d")
vec_obj["b"] # Output: 21
Lists
Let’s define a list with some elements and use the names() function to get the names.
# Create a list
list_obj <- list(name = "Krunal", age = 31, city = "Rajkot")
# Get names
names(list_obj) # Output: "name" "age" "city"
# Accessing elements by name
person$age # Output: 27
Here, the names() function retrieves the keys(names) of the elements of the list. The names are: “name”, “age”, and “city”.
Data Frames
When you are working with data frames, and you will use the names() function, it will return the names of the columns.
# Creating a data frame
df <- data.frame(
Name = c("Krunal", "Ankit", "Dhaval"),
Age = c(25, 30, 22),
City = c("London", "Paris", "Perth")
)
# Getting column names
names(df) # Output: "Name" "Age" "City"
# Accessing columns by name
df$Age # Output: 25 30 22
Removing names
If you want to remove names from an object, assign that object’s name to NULL.
names(obj) <- NULL
For matrices, there are already two functions available: rownames() and colnames().
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.