How to Rename Column by Index Position Using dplyr


You can use the following syntax to rename a column of a data frame by index position using dplyr:

Method 1: Rename One Column by Index

#rename column in index position 1
df %>%
  rename(new_name1 = 1)

Method 2: Rename Multiple Columns by Index

#rename column in index positions 1, 2, and 3
df %>%
  rename(new_name1 = 1,
         new_name2 = 2,
         new_name3 = 3)

The following examples show how to use this syntax in practice.

Example 1: Rename One Column by Index

The following code shows how to use the rename() function to rename one column by index position:

library(dplyr)

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
                 points=c(12, 14, 19, 24, 24, 22, 30, 9),
                 assists=c(4, 6, 6, 8, 3, 7, 8, 11))

#rename column in index position 1
df <- df %>%
        rename(team_new = 1)

#view updated data frame
df

  team_new points assists
1        A     12       4
2        A     14       6
3        A     19       6
4        A     24       8
5        B     24       3
6        B     22       7
7        B     30       8
8        B      9      11

Notice that the first column name was changed from team to team_new and all other column names remained the same.

Example 2: Rename Multiple Columns by Index

The following code shows how to use the rename() function to rename multiple columns in the data frame by index position:

library(dplyr)

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
                 points=c(12, 14, 19, 24, 24, 22, 30, 9),
                 assists=c(4, 6, 6, 8, 3, 7, 8, 11))

#rename column in index position 1
df<- df %>%
       rename(team_new = 1,
              assists_new = 3)

#view updated data frame
df

  team_new points assists_new
1        A     12           4
2        A     14           6
3        A     19           6
4        A     24           8
5        B     24           3
6        B     22           7
7        B     30           8
8        B      9          11

The column names in index position 1 and 3 changed, while the column name in index position 2 remained the same.

Additional Resources

The following tutorials explain how to perform other common functions in dplyr:

How to Select Columns by Index Using dplyr
How to Remove Rows Using dplyr
How to Replace NA with Zero in dplyr

Leave a Reply

Your email address will not be published.