How to Use rename in dplyr for Renaming Columns in R
Use
rename() from the dplyr package to change column names in a data frame by specifying new names on the left and old names on the right, like rename(data, new_name = old_name). This function keeps all other columns unchanged and returns a new data frame with updated column names.Syntax
The basic syntax of rename() is:
rename(data, new_name = old_name)
Here:
- data: your data frame or tibble.
- new_name: the new column name you want to assign.
- old_name: the current column name you want to rename.
You can rename multiple columns by adding more new_name = old_name pairs separated by commas.
r
rename(data, new_name = old_name)
# Example for multiple columns:
rename(data, new_name1 = old_name1, new_name2 = old_name2)Example
This example shows how to rename columns in a simple data frame using rename(). We rename mpg to miles_per_gallon and cyl to cylinders.
r
library(dplyr) data <- mtcars # Rename columns renamed_data <- rename(data, miles_per_gallon = mpg, cylinders = cyl) # Show first 5 rows of renamed data head(renamed_data, 5)
Output
miles_per_gallon cylinders disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Common Pitfalls
Common mistakes when using rename() include:
- Reversing the order: The new name must be on the left and the old name on the right (
new_name = old_name), not the other way around. - Using quotes around column names: Do not quote column names inside
rename(). - Trying to rename columns that do not exist will cause an error.
r
library(dplyr)
data <- mtcars
# Wrong: old name on left, new name on right (causes error)
# rename(data, mpg = miles_per_gallon)
# Correct:
rename(data, miles_per_gallon = mpg)Quick Reference
| Action | Syntax Example | Description |
|---|---|---|
| Rename one column | rename(data, new_name = old_name) | Change one column name. |
| Rename multiple columns | rename(data, new1 = old1, new2 = old2) | Change several column names at once. |
| Keep other columns | rename() only changes specified columns | All other columns stay the same. |
| No quotes | rename(data, new_name = old_name) | Do not use quotes around column names. |
| Error if old name missing | rename(data, new_name = missing_col) | Fails if old column does not exist. |
Key Takeaways
Use rename(data, new_name = old_name) to rename columns in dplyr.
Put the new column name on the left and the old name on the right without quotes.
You can rename multiple columns by adding more new_name = old_name pairs separated by commas.
rename() returns a new data frame and does not modify the original data.
Trying to rename a non-existent column causes an error.