Home » How to Rename Multiple Columns Using dplyr

How to Rename Multiple Columns Using dplyr

by Erma Khan

You can use the following functions from the dplyr package in R to rename multiple columns in a data frame:

Method 1: Use rename()

df %>% rename(new1 = old1, new2 = old2)

Method 2: Use rename_with()

new new1', 'new2')
old old1', 'old2')

df %>% rename_with(~ new, all_of(old))

Both methods produce the same result.

The following examples show how to use each of these methods in practice with the following data frame in R:

#create data frame
df frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(22, 34, 30, 12, 18),
                 assists=c(7, 9, 9, 12, 14))

#view data frame
df

  team points assists
1    A     22       7
2    B     34       9
3    C     30       9
4    D     12      12
5    E     18      14

Example 1: Rename Multiple Columns Using rename()

The following code shows how to use the rename() function to rename the team and points columns in the data frame:

library(dplyr)

#rename team and points columns
df2 % rename(team_new = team, points_new = points)

#view updated data frame
df2

  team_new points_new assists
1        A         22       7
2        B         34       9
3        C         30       9
4        D         12      12
5        E         18      14

The team and points columns have been renamed while the assists column has remained the same.

Example 2: Rename Multiple Columns Using rename_with()

The following code shows how to use the rename_with() function to rename the team and points columns in the data frame:

library(dplyr)

#define new names
new team_new', 'points_new')

#define old names to replace
old team', 'points')

#rename old names with new names
df2 % rename_with(~ new, all_of(old))

#view updated data frame
df2

  team_new points_new assists
1        A         22       7
2        B         34       9
3        C         30       9
4        D         12      12
5        E         18      14

The team and points columns have been renamed while the assists column has remained the same.

Note that this method may be easier to use when you have a long list of column names you’d like to replace.

Additional Resources

The following tutorials explain how to perform other common tasks using dplyr:

How to Select Columns by Name Using dplyr
How to Select Columns by Index Using dplyr
How to Use select_if with Multiple Conditions in dplyr

Related Posts