melbez
melbez

Reputation: 1000

Rename group of consecutive columns efficiently in R

I'm looking for an efficient way to rename several columns.

I have a dataframe that looks like the following.

id  sdf  dir  fki 
1   3    4    2
2   5    2    1
3   4    1    2

I want to rename columns sdf, dir, and fki.

I know I could do so like this:

df <- df %>% 
rename(newname1 = sdf, 
       newname2 = dir, 
       newname3 = fki)

With the amount of columns I have, it is taking a long time to type the names of the columns I would like to replace.

Ideally, I would like to create a vector with names:

newcolumns <- c("newname1", "newname2", "newname3") 

And then specify that these should replace the column names in the dataframe, starting with column sdf. Is there a way to do this?

Upvotes: 3

Views: 497

Answers (1)

akrun
akrun

Reputation: 886948

We can use rename_at

library(dplyr)
df %>%
      rename_at(vars(-id), ~ newcolumns)

-output

#   id newname1 newname2 newname3
#1  1        3        4        2
#2  2        5        2        1
#3  3        4        1        2

Or with rename_with

df %>%
   rename_with(~ newcolumns, -id)

Or pass a named vector and use !!! in rename

df %>%
    rename(!!! setNames(names(df)[-1], newcolumns))

Or using base R

names(df)[-1] <- newcolumns

data

df <- structure(list(id = 1:3, sdf = c(3L, 5L, 4L), dir = c(4L, 2L, 
1L), fki = c(2L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-3L))

Upvotes: 3

Related Questions