Renaming columns means changing the existing column names to more meaningful or consistent ones. We often do this to make our data easier to understand, follow naming rules or match analysis requirements. In R, you can rename multiple columns using base R functions or packages like dplyr.
Column names can be modified using colnames() or names().
The dplyr::rename() function provides a clean and readable approach.
Multiple columns can be renamed at once efficiently.
Using names()
We use names() to assign a new vector of names to all columns at once.
names(): Retrieves or sets the names of columns in a data frame.
c(): Combines values into a vector.
data.frame(): Creates a table like structure.
cat(): Prints text without quotes or structure formatting.
The column names are changed from oldName1, oldName2, oldName3 to newName1, newName2, newName3, while the data remains unchanged. The output confirms the renaming in a data.table format.