I would like to replace different values in a vector with specific other values at once.
In the problem I'm working through:
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?
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.
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.
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:
old
with the values that need to be replaced and new
with the corresponding replacements.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
valuesnew
.new
to the positions of x
that are present in old
: x[x %in% old]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With