change_values.Rd
Replaces specific values in a vector with new values, using formula-style syntax.
change_values(x, ..., .default = NULL)
A vector whose values will be recoded.
One or more replacement rules in the form old ~ new
. Each rule specifies a value in x
to be replaced.
Optional. A default value assigned to all elements not explicitly matched in the replacement rules. If NULL
(default), unmatched values remain unchanged.
A vector with values replaced according to the specified rules. If x
is numeric and at least one replacement is a character string, the result will be coerced to character.
recode()
, ifelse()
, case_when()
# Basic recoding
change_values(c(1, 2, 3, NA), 2 ~ "two", 3 ~ "three")
#> [1] "1" "two" "three" NA
# Assign a default value to unmatched entries
change_values(c(1, 2, 3), 2 ~ "two", .default = "default")
#> [1] "default" "two" "default"
# Unmatched values remain unchanged (no warning or error)
change_values(c(1, 2, 3), 4 ~ "four")
#> [1] "1" "2" "3"
# Recode missing values (NA)
change_values(c(NA, 1, NA, 2), NA ~ "This is a missing value")
#> [1] "This is a missing value" "1"
#> [3] "This is a missing value" "2"