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.
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.
Why Select & Rename?
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..."
The select() Function
Visualizing select()
select() Helper Functions
select() supports powerful helper functions that let you pick columns by pattern instead of listing them one by one.
Excluding Columns with select()
Sometimes it is easier to say what you don't want. Use the minus sign - to drop columns.
The rename() Function
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
Example 1: Basic select()
You have a dataset of weather observations. You only need date and temperature.
Example 2: select() + rename()
Now let's rename temp_f to something clearer, all in one pipeline.
Example 3: Helpers + Exclusion
A school survey has columns q1 through q10, plus student_id and timestamp. You want only the question columns.
Common Mistakes
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()?