Logo

How to change column names of a data frame in R?

If you have a data frame df and want to rename all columns, you can do:

names(df) <- c("new_name1", "new_name2", "new_name3")

Ensure you have exactly as many new names as there are columns in df.

Using colnames()
colnames() is functionally similar to names() for data frames. For instance:

colnames(df) <- c("colA", "colB", "colC")

Either approach gives the same result.

Using dplyr::rename()
If you only need to rename some columns or prefer a pipe-friendly syntax:

library(dplyr) df <- df %>% rename( new_col_name1 = old_col_name1, new_col_name2 = old_col_name2 )

rename() maps new_name = old_name. You don’t need to rename every column at once; only specify those that need changes.

Pro Tips

  • Validate you’re not introducing duplicate names.
  • Always check your data after renaming to avoid referencing old column names in subsequent code.

Further Skill-Building
If you’d like to polish your data manipulation and interview problem-solving skills, consider:

For designing scalable and efficient systems, explore Grokking System Design Fundamentals. Get personalized feedback through Coding Mock Interviews, led by ex-FAANG engineers, and check out the DesignGurus.io YouTube channel for quick, insightful tutorials.

CONTRIBUTOR
TechGrind