Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchange two elements of a vector in one call

Tags:

r

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?

like image 476
Delrog Avatar asked Sep 09 '15 04:09

Delrog


People also ask

How do you swap two values in a vector?

swap(B) and swaps the contents. The std::vector::swap function exchanges the contents of one vector with another. It swaps the addresses(i.e. the containers exchange references to their data) of two vectors rather than swapping each element one by one which is done in constant time O(1).

Can we swap 2 vectors?

To swap two vectors, you need only swap each of these members. By swapping the pointers, this vector will point to the other vector's data on the free store and the other will point to this one's data.

Which function is used to swap two vectors?

vector::swap() This function is used to swap the contents of one vector with another vector of same type and sizes of vectors may differ.


2 Answers

How about just x[c(i,j)] <- x[c(j,i)]? Similar to replace(...), but perhaps a bit simpler.

swtch <- function(x,i,j) {x[c(i,j)] <- x[c(j,i)]; x} 
swtch(c(9,6,3,4,2,1,5,7,8) , 2,5)
# [1] 9 2 3 4 6 1 5 7 8
like image 175
jlhoward Avatar answered Oct 10 '22 19:10

jlhoward


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.

like image 27
Rich Scriven Avatar answered Oct 10 '22 19:10

Rich Scriven