R/transform_name.R

Defines functions transform_name

Documented in transform_name

#' Transforms the input to a string which can be properly saved.
#' @description
#' This function transforms the input to a string which
#' can be properly saved, i.e. transforms upper case characters to lower case
#' characters, replaces umlauts and the German eszett, removes special
#' characters and replaces white spaces by an underscore.
#' @param x
#' Any character.
#' @param back
#' If \code{back} equals \code{TRUE}, the function tries to transform the input
#' back to its original form.
#' @return
#' The transformed version of \code{x}.
#' @examples
#' transform_name(x = transform_name(x = "Max Mustermann"), back = TRUE)

transform_name <- function(x, back = FALSE) {
  stopifnot(is.character(x))
  stopifnot(length(x)==1)
  stopifnot(is.logical(back))
  if(back){
    x <- gsub("_"," ",x)
    x <- strsplit(x, " ")[[1]]
    x <- gsub("([\\w])([\\w]+)", "\\U\\1\\L\\2", x, perl = TRUE)
    x <- paste(x, collapse = " ")
  } else {
    x <- tolower(x)
    x <- sub("\\u00df","ss",x)
    x <- stringi::stri_trans_general(x, "de-ASCII; Latin-ASCII")
    x <- gsub("[^0-9A-Za-z///' ]", "", x, ignore.case = TRUE)
    x <- gsub(" ","_",x)
  }
  return(x)
}
loelschlaeger/personfiles documentation built on Dec. 21, 2021, 11:45 a.m.