Direct assignment should do it:

x[c(2,3)] <- x[c(3,2)]

--MC
--
Martin Corley




On 15 April 2014 18:55:57 "Hofmeister, Philip" <[email protected]> wrote:

this is probably more appropriate for a general R listserv, but i'm more likely to get an answer i can decipher here. apologies also for what is likely a simple fix, but i can't seem to find the right term or syntax to get this to work without writing ugly code.

i want to swap values in a vector, e.g.
x <- c(1, 2, 3)
[1] 1 2 3

and get back
1 3 2
i can do this by saving the 2nd or 3rd element of the vector elsewhere, replacing one of the vector elements (x[3] <- x[2]), and then restoring the stored value, but that seems wasteful. surely there is a function like swap() or std::swap(a, b), but i can't seem to find anything. anyone have any ideas?
ph







The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.

Reply via email to