Applying dplyr's rename to all columns while using pipe operator

前端 未结 5 1290

I\'m working with an imported data set that corresponds to the extract below:

set.seed(1)
dta <- data.frame(\"This is Column One\" = runif(n = 10),
               


        
5条回答
  •  鱼传尺愫
    2021-01-04 03:36

    I know this is an old question, and I'm sure you found the solution by now, but I stumbled here searching for the same question, and ultimately found a few new ways to do this.

    Dplyr

    Using dplyr 0.6.0 and above, there is now a rename_all function:

      dta %>% 
        rename_all(funs(gsub("[[:punct:]]", "", make.names(names(dta)))))
    

    Which works, but it's a little messy to me. If you want more flexibility with dplyr, you can also call on:

    • rename_at
    • rename_if

    Janitor

    This is a pretty nice package (with plenty of additional utility) that can easily clean up column names:

    library(janitor)
    
    dta %>% 
      clean_names()
    

    Which will rename and clean all column names to the following:

    [1] "this_is_column_one"  "another_amazing_column_name"  "x_this_columns_is_so_special"
    

    Everything becomes snake_case rather than CamelCase, but overall clean_names is very flexible in the column names it handles. If that IS a deal breaker, you can use yet another package snakecase for its function to_big_camel_case() within the rename_all function...although that is starting to get a little too esoteric

提交回复
热议问题