[R-lang] Re: swapping values without temporary storage
Scott Jackson
scottuba@gmail.com
Tue Apr 15 11:22:55 PDT 2014
I think just writing a quick function would be the way to go here. Would
this do what you want?
swap <- function(x, a, b) {
out <- x
out[a] <- x[b]
out[b] <- x[a]
out
}
y <- 1:10
swap(y, 2, 8)
[1] 1 8 3 4 5 6 7 2 9 10
-scott
On Tue, Apr 15, 2014 at 2:05 PM, João Veríssimo <jl.verissimo@gmail.com>wrote:
> Perhaps rev() can help?
>
> Maybe something like:
>
> x <- c("a", "b", "c")
> c(x[1], rev(x[2:3]))
>
> João
> On Tue, 2014-04-15 at 17:52 +0000, Hofmeister, Philip 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
> >
> >
> >
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.ucsd.edu/pipermail/ling-r-lang-l/attachments/20140415/5428063c/attachment.html
More information about the ling-r-lang-L
mailing list