01 / 21

select() & rename()

Learn how to choose specific columns from a data frame with select() and give them clear, meaningful names with rename() using the tidyverse in R.

Data Science R Programming

What is a Data Frame?

A data frame is the most common way to store data in R. Think of it like a spreadsheet: rows are observations and columns are variables. Real-world data frames often have dozens or hundreds of columns, but you usually only need a few at a time.

name age grade score city Alice 16 10th 92 Portland Bob 17 11th 85 Seattle Carol 16 10th 97 Denver ... 5 columns (variables) x many rows (observations)

Why Select & Rename?

Focus
Keep only the columns you need so your data is easier to read and work with.
Clarity
Rename cryptic column names like x1 to meaningful names like temperature.
Efficiency
Smaller data frames use less memory and make downstream analysis faster.

The Pipe Operator

Before we dive in, let's meet the pipe operator: %>%. It takes the result from the left side and feeds it as the first argument to the function on the right. Think of it as saying "and then..."

# Without pipe select(students, name, score) # With pipe (reads top to bottom) students %>% select(name, score)

The select() Function

select(.data, column1, column2, ...)
1
.data: the data frame you want to work with (or piped in via %>%).
2
column1, column2, ...: names of columns to keep. No quotes needed!
3
Returns a new data frame with only the listed columns, in the order you specify.

Visualizing select()

Original: students name age grade score city Alice 16 10th 92 PDX Bob 17 11th 85 SEA Carol 16 10th 97 DEN → select(name, score) Result name score Alice 92 Bob 85 Carol 97 students %>% select(name, score) Only the green-highlighted columns survive

select() Helper Functions

select() supports powerful helper functions that let you pick columns by pattern instead of listing them one by one.

starts_with()
Columns starting with a prefix: starts_with("math")
ends_with()
Columns ending with a suffix: ends_with("_score")
contains()
Columns containing a string: contains("temp")
num_range()
Numbered columns: num_range("q", 1:5) selects q1 through q5
# Select all columns that start with "math" students %>% select(starts_with("math"))

Excluding Columns with select()

Sometimes it is easier to say what you don't want. Use the minus sign - to drop columns.

# Drop the city column students %>% select(-city) # Drop multiple columns students %>% select(-age, -grade) # Drop columns by helper students %>% select(-starts_with("temp"))

The rename() Function

rename(.data, new_name = old_name)
1
new_name: the name you want the column to have (goes on the left of =).
2
old_name: the name the column currently has (goes on the right of =).
3
Returns the full data frame with all columns intact: only the specified names change.

select() vs rename()

select() rename()
Purpose Choose which columns to keep Change column names
Columns returned Only the ones you list All columns (names updated)
Can rename? Yes (new = old syntax) Yes (primary purpose)
Can drop columns? Yes (with - sign) No
Typical use case Narrow down your data Clean up column names

Step-by-Step Workflow

1
Load tidyverse: library(tidyverse)
2
Inspect your data: Use names(df) or glimpse(df) to see all column names.
3
Decide what to keep: List the columns you need, or identify the ones to remove.
4
Apply select(): df %>% select(col1, col2) to keep, or select(-col3) to drop.
5
Apply rename() if needed: df %>% rename(new = old) to fix unclear names.
6
Save the result: Assign back with df_clean <- df %>% ...

Example 1: Basic select()

You have a dataset of weather observations. You only need date and temperature.

# weather has: date, temp_f, humidity, wind_mph, precip_in weather_simple <- weather %>% select(date, temp_f) # Result: only date and temp_f columns remain head(weather_simple)
date temp_f 2024-01-01 32 2024-01-02 28 2024-01-03 35 3 columns dropped: humidity, wind_mph, precip_in

Example 2: select() + rename()

Now let's rename temp_f to something clearer, all in one pipeline.

# Select and rename in one step weather_clean <- weather %>% select(date, temperature = temp_f) # Or use both functions chained weather_clean <- weather %>% select(date, temp_f) %>% rename(temperature = temp_f)

Example 3: Helpers + Exclusion

A school survey has columns q1 through q10, plus student_id and timestamp. You want only the question columns.

# Use num_range to grab q1 through q10 survey_qs <- survey %>% select(num_range("q", 1:10)) # Or exclude the two you don't need survey_qs <- survey %>% select(-student_id, -timestamp) # Then rename for clarity survey_clean <- survey_qs %>% rename( math_interest = q1, study_hours = q2, sleep_quality = q3 )

Common Mistakes

✕ Wrong rename order
Writing rename(old = new) instead of rename(new = old). The new name always goes on the left.
✕ Quoting column names
Using select("name") with quotes. In dplyr, column names are unquoted: select(name).
✕ Forgetting to save
Running df %>% select(...) without assigning with <-. The original df stays unchanged.

Quick Reference Table

Task Code
Keep specific columns select(col1, col2)
Drop a column select(-col)
Select by prefix select(starts_with("x"))
Select by suffix select(ends_with("_id"))
Select + rename select(new = old)
Rename only rename(new = old)
Reorder columns select(col3, col1, col2)

Question 1 of 5

Which function keeps only the columns you specify and drops the rest?

Question 2 of 5

What is the correct syntax to rename column avg_temp to temperature?

Question 3 of 5

You run df %>% select(-age, -city). What happens?

Question 4 of 5

What does df %>% select(starts_with("score")) return?

Question 5 of 5

What is the key difference between select() and rename()?