Home > Software engineering >  How to rename column 5 through column 66 as x1:x62 with dplyr?
How to rename column 5 through column 66 as x1:x62 with dplyr?

Time:09-27

How to rename column 5 through column 66 as x1:x62 with dplyr? Old names are arbitrary and without a pattern.

CodePudding user response:

We can use rename_with

library(dplyr)
library(stringr)
df1 %>%
    rename_with(~ str_c("x", seq_along(.x)), 5:66)

CodePudding user response:

In base R:

colnames(df1[5:66]) <- paste0("x", 1:62)

With dplyr syntax:

library(dplyr)
df1 %>% 
  `colnames<-`(c(colnames(df1[1:5]), paste0("x", 1:62), colnames(df1[68:ncol(df1)])))
  • Related