Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple values at once [duplicate]

Tags:

r

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?

like image 356
LatteMaster Avatar asked Jun 17 '18 16:06

LatteMaster


People also ask

How do you find and replace multiple values at once in Word?

Go to Home > Replace. Enter the word or phrase you want to replace in Find what. Enter your new text in Replace with. Choose Replace All to change all occurrences of the word or phrase.

How do you replace multiple values in SQL?

Using the REPLACE() function will allow you to change a single character or multiple values within a string, whether working to SELECT or UPDATE data.


1 Answers

A possible solution using match:

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

x[x %in% old] <- new[match(x, old, nomatch = 0)]

which gives:

> x
[1] 8 4 0 5 1 5 7 9

What this does:

  • Create two vectors: old with the values that need to be replaced and new with the corresponding replacements.
  • Use match to see where values from x occur in old. Use nomatch = 0 to remove the NA's. This results in an indexvector of the position in old for the x values
  • This index vector can then be used to index new.
  • Only assign the values from new to the positions of x that are present in old: x[x %in% old]
like image 173
Jaap Avatar answered Dec 01 '22 21:12

Jaap