R/clean_names.R

#' Create Syntatically Valid Names
#'
#'@description A wrapper for the \code{make.names()} function to make syntatically
#'    valid names using my preferred syntax.
#'
#'@details Replaces spaces with underscore
#'
#'    Sets all letters to lower case
#'
#'    Injects an "x" before a syntatically invalid beginning (e.g. a number, or symbol)
#'
#'    Indicates duplicate names with a "_n", where n is the nth duplicate
#'
#'@param df Any object with a name, but I typically use them for data frames, hence "df".
#'
#'
#'@return Returns the object you fed it with changed names.
#'
#'@examples
#' # Using a data.frame
#' df <- data.frame("Happy Boy" = c(1:10),
#'                 "3BeeSoup    " = c(letters[1:10]),
#'                 "Happy Boy" = c(10:1))
#'
#' clean_names(df)
#'
#' # Using a tibble
#' df2 <- dplyr::tibble(`Happy Boy` = c(1:10),
#'                       `3BeeSoup    ` = c(letters[1:10]))
#'
#' clean_names(df2)
#' @export
clean_names <- function(df){
  names(df) <- tolower(gsub("\\.", "_", make.names(names(df), unique = TRUE)))
  return(df)
}
christian-million/researchR documentation built on May 15, 2019, 12:45 p.m.