Quantcast
Channel: R: Swap two variables without using a third - Stack Overflow
Browsing latest articles
Browse All 9 View Live

Answer by GKi for R: Swap two variables without using a third

You can temporary store values in a list and also make an assignment inside it. But I don't recommend this way, just to show another possibility.a <- 1b <- 2b <- list(a, a <- b)[[1]]a#[1]...

View Article



Answer by LeoR for R: Swap two variables without using a third

Based on Nathan's post, to keep the variable-swap within the running environment:x <- 10y <- 20list2env(list(x=y, y=x), envir=as.environment(environment()))print(x)print(y)

View Article

Answer by Nathan Werth for R: Swap two variables without using a third

The good thing about having way too many functions in the base package: there's always a way to do something, even if it's a bad idea.list2env(list(a = b, b = a), envir = .GlobalEnv)This works no...

View Article

Answer by Voltaire for R: Swap two variables without using a third

To the best of my knowledge there is no built in function to do this, and no general way you can swap two variables without having a third. However, if you are after a function that will at least...

View Article

Answer by Matheus Avellar for R: Swap two variables without using a third

While the previous answers are all fine and pretty, they all take up too much space for my liking!So I've come up with a tidier solution in C:a = (b - a) + (b = a);It doesn't work with strings, but...

View Article


Answer by Jens Krüger for R: Swap two variables without using a third

StartA = 9B = 5A = A + B Then A is 14B is 5B = A - BThen A is 14B is 9A = A - B Result:A(5) is now BB(9) is now ANot really simpler then just using a third variable but i works!

View Article

Answer by Mateusz Kleinert for R: Swap two variables without using a third

There is general solution or 'trick' for that:a <- 1b <- 2a <- a + bb <- a - ba <- a - bHere's a useful link that explains a lot: xor-trick

View Article

Answer by Ronak Shah for R: Swap two variables without using a third

For integers, you can usea = a + bb = a - ba = a - band for strings, this would worka <- "one"b <- "two"a <- paste(a,b, sep = "")b <- substr(a,0,nchar(a) - nchar(b))a <-...

View Article


R: Swap two variables without using a third

I have two variables (i.e.): a <- 1 b <- 2and I would like to swap their values. Is there any built-in R function, that is able to perform that operation? Or is there an other elegant way,...

View Article

Browsing latest articles
Browse All 9 View Live


Latest Images