Skip to content

Instantly share code, notes, and snippets.

@mdlincoln
Last active October 2, 2015 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdlincoln/156473508da402f04238 to your computer and use it in GitHub Desktop.
Save mdlincoln/156473508da402f04238 to your computer and use it in GitHub Desktop.
Replace values in a vector based on a named vector dictionary
#' Replace all matching values
#'
#' @param v Vector whose values are to be replaced
#' @param pairs A named vector of replacements
#' @export
#' @examples
#' x <- c("a", "a", "b", "c")
#' p <- c("a" = "alpha", "b" = "beta")
#' replace_each(x, p)
replace_each <- function(v, pairs) {
orig <- names(pairs)
new <- unname(pairs)
for(i in 1:length(pairs))
v <- replace(v, v == orig[i], new[i])
return(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment