Replace selected values in a vector. You can pass parallel from/to vectors, or a single named vector as from (with to = NULL) whose names are matched and replaced by the corresponding values.

replace_values(x, from, to=NULL, must_have=TRUE)

Arguments

x

vector

from

values to be changed; or a named vector mapping old values (names) to new values when to is NULL

to

replacement values aligned with from; if NULL, from must be a named vector and its names/values are used as from/to

must_have

logical. Give an error if a value in from is not in x

Value

vector

Examples

v <- LETTERS[1:5]
replace_values(v, c("A", "B", "C"), c("first", "abc", "third"))
#> [1] "first" "abc"   "third" "D"     "E"    

# named map: only listed values are changed; others are left as-is
crop_map <- c(forages = "forage crop", commonbean = "common bean")
replace_values(c("maize", "forages", "commonbean"), crop_map)
#> [1] "maize"       "forage crop" "common bean"