Last active
October 2, 2015 19:48
-
-
Save mdlincoln/156473508da402f04238 to your computer and use it in GitHub Desktop.
Replace values in a vector based on a named vector dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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