Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected behavior of replace

Tags:

r

I need help with the replace() command

replace(c(3,2,2,1),1:3,4:6)

I was expecting an output of 6,5,5,4 but got 4,5,6,1

What am i doing wrong?

My understanding of what replace is this: it looks up index values of elements of the first argument in the second argument (e.g. 3 is the 3rd element in 1:3) and then replaces it with elements in the third argument with the same index (e.g. 3rd element in 4:6 is 6 thus the reason for me expecting the first element in the vector to be 6)

Thank you. (replace help file doesn't have example... need to ask for clarification here)

like image 917
morsecode Avatar asked Dec 18 '25 17:12

morsecode


2 Answers

While replace doesn't give the behaviour your desired, to achieve what you were intending is quite easy to do using match:

new[match(x,i)]
like image 182
James Avatar answered Dec 21 '25 08:12

James


It is all given in the description of replace(), just read carefully:

 ‘replace’ replaces the values in ‘x’ with indices given in ‘list’
 by those given in ‘values’. If necessary, the values in ‘values’
 are recycled.


x <- c(3, 2, 2, 1)
i <- 1:3
new <- 4:6

so this means in your case:

x[i] <- new
like image 25
mropa Avatar answered Dec 21 '25 09:12

mropa



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!