Mapping vector values

Problem

You want to change all instances of value x to value y in a vector.

Solution

  1. # Create some example data
  2. str <- c("alpha", "beta", "gamma")
  3. num <- c(1, 2, 3)

The easiest way is to use revalue() or mapvalues() from the plyr package:

  1. library(plyr)
  2. revalue(str, c("beta"="two", "gamma"="three"))
  3. #> [1] "alpha" "two" "three"
  4. mapvalues(str, from = c("beta", "gamma"), to = c("two", "three"))
  5. #> [1] "alpha" "two" "three"
  6. # For numeric vectors, revalue() won't work, since it uses a named vector, and
  7. # the names are always strings, not numbers. mapvalues() will work, though:
  8. mapvalues(num, from = c(2, 3), to = c(5, 6))
  9. #> [1] 1 5 6

If you don’t want to rely on plyr, you can do the following with R’s built-in functions.Note that these methods will modify the vectors directly; that is, you don’t have to save the result back into the variable.

  1. # Rename by name: change "beta" to "two"
  2. str[str=="beta"] <- "two"
  3. str
  4. #> [1] "alpha" "two" "gamma"
  5. num[num==2] <- 5
  6. num
  7. #> [1] 1 5 3

It’s also possible to use R’s string search-and-replace functions to remap values in character vectors.Note that the ^ and $ surrounding alpha are there to ensure that the entire string matches.Without them, if there were a value named alphabet, it would also match, and the replacement would be onebet.

  1. str <- c("alpha", "beta", "gamma")
  2. sub("^alpha$", "one", str)
  3. #> [1] "one" "beta" "gamma"
  4. # Across all columns, replace all instances of "a" with "X"
  5. gsub("a", "X", str)
  6. #> [1] "XlphX" "betX" "gXmmX"
  7. # gsub() replaces all instances of the pattern in each element
  8. # sub() replaces only the first instance in each element

See also

Changing the name of factor levels works much the same. See ../Renaming levels of a factor for more information.