Logo

How to rename a single column in a data frame in R?

Use the names() function and find the existing column name:

df <- data.frame(oldName = 1:5, otherCol = 6:10) names(df)[names(df) == "oldName"] <- "newName"

This changes the column oldName to newName while leaving all other columns unchanged.

Using dplyr
The dplyr package offers a convenient pipe-friendly approach:

library(dplyr) df <- df %>% rename(newName = oldName)

Here, newName = oldName clarifies exactly which column you’re renaming.

Pro Tips

  • Always confirm the original column name is spelled correctly, or it won’t be found.
  • Verify your data frame structure with str(df) or colnames(df) afterward to ensure the rename succeeded.

Further Learning
If you’re enhancing your coding interview preparedness or looking to master data manipulation, these DesignGurus.io courses can help:

For large-scale architecture insights, explore Grokking System Design Fundamentals. You can also sign up for a Coding Mock Interview with ex-FAANG engineers to get personalized, high-level feedback. Finally, don’t miss the DesignGurus.io YouTube channel for more tutorials.

CONTRIBUTOR
TechGrind