R dplyr: rename variables using string functions

后端 未结 8 539
说谎
说谎 2020-11-28 03:45

(Somewhat related question: Enter new column names as string in dplyr's rename function)

In the middle of a dplyr chain (%>%), I wou

相关标签:
8条回答
  • 2020-11-28 04:44

    As of 2020, rename_if, rename_at and rename_all are marked superseded. The up-to-date way to tackle this the dplyr way would be rename_with():

    iris %>% rename_with(tolower)
    

    or a more complex version:

    iris %>% 
      rename_with(stringr::str_replace, 
                  pattern = "Length", replacement = "len", 
                  matches("Length"))
    
    0 讨论(0)
  • 2020-11-28 04:47

    This is a very late answer, on May 2017

    As of dplyr 0.5.0.9004, soon to be 0.6.0, many new ways of renaming columns, compliant with the maggritr pipe operator %>%, have been added to the package.

    Those functions are:

    • rename_all
    • rename_if
    • rename_at

    There are many different ways of using those functions, but the one relevant to your problem, using the stringr package is the following:

    df <- df %>%
      rename_all(
          funs(
            stringr::str_to_lower(.) %>%
            stringr::str_replace_all(., '\\.', '_')
          )
      )
    

    And so, carry on with the plumbing :) (no pun intended).

    0 讨论(0)
提交回复
热议问题