Taming the Nameless: Using the names() Function in R
code
rtip
operations
dplyr
datatable
Author
Steven P. Sanderson II, MPH
Published
March 8, 2024
Introduction
Have you ever created a dataset in R and ended up with a bunch of unnamed elements? It can make your code clunky and hard to read. Fear not, fellow R wranglers! The names() function is here to save the day.
What is the names() function?
Think of names() as your data janitor, cleaning up and assigning names to the elements in your objects. It’s a chameleon, working with vectors, lists, data frames, and more!
How does it work?
names() can be used in two ways:
Extracting Names: Want to see what names are already assigned? Simply use names(your_object). This will return a character vector showing the current names.
Assigning Names: Want to give your elements some meaningful titles? Use names(your_object) <- c("name1", "name2", ...). Here, c() creates a character vector with your desired names, and the assignment operator (<-) puts them in place.
Let’s see it in action!
Example 1: Naming a Vector
# Create an unnamed vectormy_data <-c(23, 5, 99)# Check the names (there are none!)names(my_data)
NULL
# Assign names using c()names(my_data) <-c("age", "height", "iq")# Print the data with namesmy_data
age height iq
23 5 99
In this example, we started with an unnamed vector. We then used names() to see there were no existing names. Finally, we assigned clear names using c() and the assignment operator.
Example 2: Naming a List
# Create an unnamed listmy_info <-list(score =87, games =10)# Peek at the names (default is numeric order)my_info
$score
[1] 87
$games
[1] 10
# Assign new namesnames(my_info) <-c("exam_score", "num_games")# Print the list with namesmy_info
$exam_score
[1] 87
$num_games
[1] 10
Here, we created a list with default numeric names. We used names() to see these, then replaced them with more descriptive names.
Example 3: Renaming Data Frame Columns
# Sample data frame (mtcars comes with R)head(mtcars) # Peek at the data
This example shows how names() can be used with data frames. We access the column position (index 3) and assign a new name using double square brackets ([[ ]]).
Give it a Try!
Now it’s your turn! Grab some data and play with names(). Here are some ideas:
Create a vector of temperatures and name them for the days of the week.
Build a list of your favorite movies and assign names for genre and year.
Explore a built-in R dataset and rename some columns for clarity.
By using names(), you’ll make your code more readable and your data analysis smoother. Happy naming!