I want to do multiple replacements in the matrix. For example,
x <-sample(1:20,50,rep=T)
replace(x, x == 4, 2)
Replacing the elements equal to 4 in x with 2 by using replace. But how can I replace x == 4
with 2
, x ==3
with 4
and x == 5
with 6
.
Is there any built function to replace (4,3,5)
respectively with (2,4,6)
?
1) Try this:
2) Here is a more general approach:
This second approach has the form:
c(new, x)[match(x, c(old, x))]
I smell a data.table answer cooking but here's an environment lookup approach:
This one begged for a benchmark:
On 10,000 length vector (10 replications):
You can do this:
or use
plyr
'smapvalues
which uses a similar implementation usingmatch
:Both methods work with any kind of data. For character vectors, you could also convert into factors and permute levels.