R dplyr: rename variables using string functions

后端 未结 8 586
说谎
说谎 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

    In case you don't want to write the regular expressions yourself, you could use

    • the snakecase-pkg which is very flexible,
    • janitor::make_clean_names() which has some nice defaults or
    • janitor::clean_names() which does the same as make_clean_names(), but works directly on data frames.

    Invoking them inside of a pipeline should be straightforward.

    library(magrittr)
    library(snakecase)
    
    iris %>% setNames(to_snake_case(names(.)))
    iris %>% tibble::as_tibble(.name_repair = to_snake_case)
    iris %>% purrr::set_names(to_snake_case)
    iris %>% dplyr::rename_all(to_snake_case)
    iris %>% janitor::clean_names()
    
    

提交回复
热议问题