[R-lang] Re: swapping values without temporary storage

Ewan Dunbar ewan.dunbar@alumni.utoronto.ca
Tue Apr 15 11:44:01 PDT 2014


hi philip -
reordering elements of vectors can be done easily in R using indexing:

# vector with elements 6 and 3 swapped
x <- c(10, 12, 24, 42, 15, 17)
[1] 10 12 24 42 15 17
x <- x[c(1:2, 6, 4:5, 3)]
[1] 10 12 17 42 15 24

or, to be a bit more transparent about it:

# swap values in positions m and n
if (n < length(x)) {
	new_order <- c(1:(m-1), n, (m+1):(n-1), m, (n+1):length(x))
} else {
	new_order <- c(1:(m-1), n, (m+1):(n-1), m)
}
x <- x[new_order]

hth -e

Le 15 avr. 2014 à 19:52, Hofmeister, Philip <phofme@essex.ac.uk> a écrit :

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




More information about the ling-r-lang-L mailing list