R/mgsub.R

#' @title Multiple replacements with gsub
#'
#' @description A function to run multiple gsub commands at once on a single string; if you hve many patterns and many replacements, this is very efficient code. Taken from https://stackoverflow.com/questions/15253954/replace-multiple-letters-with-accents-with-gsub


#' @param pattern vector containing one or more regular expressions (or character string for fixed = TRUE) to be matched in the given character vectors.
#' @param replacement vector containing one or more replacements for matched pattern. Must be the same length as pattern.
#' @param x a character vector where matches are sought, or an object which can be coerced by as.character to a character vector.
#' @return vector x with substituted values
#' @export

# Function to do multiple gsub replacements on a single string
# The primary use case is to swap several different pairs of values at once on a single string

mgsub = function(pattern, replacement, x) {

  if(class(x) != "character"){
    stop('class is not \'character\'')
  }

  if (length(pattern) != length(replacement)) {
    stop("pattern and replacement do not have the same length.")
  }

  result = x
  for (i in 1:length(pattern)) {
    result = gsub(pattern[i], replacement[i], result, fixed = T)
  }
  return(result)
}
bvidgen/tc documentation built on May 9, 2019, 2:21 a.m.