'How to replace multiple values at once [duplicate]

I would like to replace different values in a vector with specific other values at once.

In the problem I'm working through:

  • 1 should be replaced with 2,
  • 2 with 4,
  • 3 with 6,
  • 4 with 8,
  • 5 with 1,
  • 6 with 3,
  • 7 with 5 and
  • 8 with 7.

So that:

x <- c(4, 2, 0, 7, 5, 7, 8, 9)
x
[1] 4 2 0 7 5 7 8 9

would be converted to:

[1] 8 4 0 5 1 5 7 9

after the replacements.

I have tried using:

x[x == 1] <- 2
x[x == 2] <- 4

and so on, but that results in 1 getting replaced with 7.

What is the simplest solution to this problem without using any packages?

r


Solution 1:[1]

If one can define conversion pair for all values then converting to factor and then back to integer can be an option.

old <- 0:9
new <- c(0,2,4,6,8,1,3,5,7,9)

as.integer(as.character(factor(x, old, new)))
# [1] 8 4 0 5 1 5 7 9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MKR