Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace() function with multiple values simultaneously recoded in r [duplicate]

Tags:

r

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)?

like image 890
user1784579 Avatar asked Aug 26 '26 12:08

user1784579


1 Answers

1) Try this:

 replace(seq(20), c(4,3,5), c(2,4,6))[x]

2) Here is a more general approach:

 c(2, 4, 6, x)[match(x, c(4, 3, 5, x))]

This second approach has the form: c(new, x)[match(x, c(old, x))]

like image 77
G. Grothendieck Avatar answered Aug 29 '26 07:08

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!