Skip to content

Instantly share code, notes, and snippets.

@mdlincoln
Last active Oct 2, 2015
Embed
What would you like to do?
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