Search code examples
dplyrtidyverse

in R dplyr package, a question about function rename_with()


There is data.frame ori_df, i want to change the column names using rename_with(),but failed. Anyone can help on this ?Thanks!

 library(tidyverse)
    ori_df <- data.frame(my_item=c('a','b','c'),
                         'y2021'=c(1,4,5),
                         'y2022'=c(9,8,7))
#blow code show error message : Error: Can't convert a character vector to function
ori_df_final <- ori_df %>% rename_with(.,c('item','2021','2022'))
    

Solution

  • To use rename_with, you need to provide a function. In this case, we can just pass a character vector of the new names to replace all column names. If you have a larger dataframe and only want change a few names, then you can select those as normal with dplyr (e.g., c(my_item, y2021, y2022) instead of everything()).

    library(dplyr)
    
    ori_df %>% 
       rename_with(~ c('item','2021','2022'), everything())
    
    #  item 2021 2022
    #1    a    1    9
    #2    b    4    8
    #3    c    5    7
    

    If you are replacing all columns, then everything() is the default for the .cols argument, so you can just write:

    ori_df %>% 
        rename_with(~c('item','2021','2022'))