R/make_tidy_colnames.R

Defines functions make_tidy_colnames

Documented in make_tidy_colnames

#' ruf

#' @name make_tidy_colnames
#' @param .data class: data frame
#' @param unique class: boolean
#' @import tidyverse
#' @examples
#' make_tidy_colnames(data, unique = FALSE)
#' @export
make_tidy_colnames <- function(.data, unique = FALSE) {
  n <- if (is.data.frame(.data)) {colnames(.data)} else{.data}
  
  n <- gsub("%+", "_pct_", n)
  n <- gsub("\\$+", "_dollars_", n)
  n <- gsub("\\++", "_plus_", n)
  n <- gsub("-+", "_", n)
  n <- gsub("\\*+", "_star_", n)
  n <- gsub("#+", "_cnt_", n)
  n <- gsub("&+", "_and_", n)
  n <- gsub("@+", "_at_", n)
  n <- gsub("[^a-zA-Z0-9_]+", "_", n)
  n <- gsub("([A-Z][a-z])", "_\\1", n)
  n <- tolower(trimws(n))
  n <- gsub("(^_+|_+$)", "", n)
  n <- gsub("_+", "_", n)
  
  if (unique) n <- make.unique(n, sep = "_")
  
  if (is.data.frame(.data)) {
    colnames(.data) <- n
    .data
  } else {
    n
  }
}
nelsonroque/ruf documentation built on March 11, 2021, 2:53 p.m.