Search code examples
rfunctional-programmingdplyrdo.callpurrr

Rename column with dplyr with functional programming


I want to rename many colums. Now I rewrite the statment for each column:

df <- data.frame(col1 = 1:4, col2 = c('a', 'b', 'c', 'd'), col3 = rep(1,4))
df %>% 
    rename(col1 = col1_new) %>%
    rename(col2 = col2_new) %>%
    rename(col3 = col3_new)

How do I avoid the duplication of the rename statement? Is there a solution using functional programming with R?


Solution

  • It is easier to use setNames than with rename

    df %>% 
       setNames(., paste0(names(.), "_new"))
    #   col1_new col2_new col3_new
    #1        1        a        1
    #2        2        b        1
    #3        3        c        1
    #4        4        d        1
    

    If there is no limitation such as all the steps should be done within the %>%, a more easier and general approach is

    colnames(df) <- paste0(colnames(df), "_new")