morsecode
morsecode

Reputation: 67

unexpected behavior of replace

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)

Upvotes: 2

Views: 160

Answers (3)

James
James

Reputation: 66834

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

Upvotes: 6

mropa
mropa

Reputation: 11842

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

Upvotes: 4

Marco
Marco

Reputation: 9604

That command says to take the vector c(3, 2, 2, 1) and to replace the components with indices in 1:3 by the values given by the vector 4:6. This gives c(4, 5, 6, 1).

Upvotes: 2

Related Questions