How to Rename Columns in Data Frames in R
When you need to rename columns in a data frame, dplyr::rename() is the cleanest approach for named renames inside a pipeline, while data.table::setnames() renames by reference for very large data frames. Both methods avoid the positional fragility of index-based renaming and read more clearly than the equivalent base R assignment.
library(dplyr)
# dplyr: single and multiple renames
df <- rename(df, new_name = old_name)
df <- rename(df, new_name1 = old_name1, new_name2 = old_name2)
# rename_with() for bulk pattern-based renames
df <- rename_with(df, toupper)
df <- rename_with(df, ~ paste0("prefix_", .x), starts_with("x"))
Base R uses names() or colnames(): names(df)[names(df) == "old_name"] <- "new_name". For renaming by position, names(df)[1] <- "new_first_column" works directly. The choice between rename() and select() matters — rename() keeps all columns, while select() can reorder and drop columns too. A common pre‑processing step normalizes all column names to lowercase and replaces spaces with underscores: rename_with(df, ~ tolower(gsub(" ", "_", .x))). The janitor package provides clean_names() for more thorough cleanup.
library(data.table)
dt <- as.data.table(df)
# Rename columns by reference (no copy)
setnames(dt, "old_name", "new_name")
setnames(dt, c("old1", "old2"), c("new1", "new2"))
For interactive work where you see all current names first, names(df) prints the vector in the console so you can copy-paste the exact column name into your rename() call.
See also
- dplyr::select(), Select and rename columns
- dplyr::filter(), Filter rows
- dplyr::mutate(), Add or modify columns