Delrog Delrog - 2 months ago 8
R Question

Exchange two elements of a vector in one call

I have a vector

c(9,6,3,4,2,1,5,7,8)
, and I want to switch the elements at index 2 and at index 5 in the vector. However, I don't want to have to create a temporary variable and would like to make the switch in one call. How would I do that?

Answer

You could use replace().

x <- c(9, 6, 3, 4, 2, 1, 5, 7, 8)
replace(x, c(2, 5), x[c(5, 2)])
# [1] 9 2 3 4 6 1 5 7 8

And if you don't even want to assign x, you can use

replace(
    c(9, 6, 3, 4, 2, 1, 5, 7, 8), 
    c(2, 5), 
    c(9, 6, 3, 4, 2, 1, 5, 7, 8)[c(5, 2)]
)
# [1] 9 2 3 4 6 1 5 7 8

but that's a bit silly. You will probably want x assigned to begin with.

Comments