Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Swap two variables without using a third

Tags:

r

I have two variables (i.e.):

   a <- 1
   b <- 2

and 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, without using a third (temp) variable?

Note: If possible applicable on strings, or other datatypes.

like image 471
maRtin Avatar asked Sep 15 '15 12:09

maRtin


4 Answers

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 matter what the classes of a and b are. But I repeat: this is a bad idea.

like image 155
Nathan Werth Avatar answered Oct 17 '22 18:10

Nathan Werth


There is general solution or 'trick' for that:

a <- 1
b <- 2

a <- a + b
b <- a - b
a <- a - b

Here's a useful link that explains a lot: xor-trick

like image 25
Mateusz Kleinert Avatar answered Oct 17 '22 20:10

Mateusz Kleinert


For integers, you can use

a = a + b
b = a - b
a = a - b

and for strings, this would work

a <- "one"
b <- "two"
a <- paste(a,b, sep = "")
b <- substr(a,0,nchar(a) - nchar(b))
a <- substr(a,nchar(b) + 1, nchar(a))

> a
# two
> b 
# one
like image 9
Ronak Shah Avatar answered Oct 17 '22 20:10

Ronak Shah


Start

A = 9
B = 5
A = A + B   

Then

A is 14
B is 5
B = A - B

Then

A is 14
B is 9
A = A - B 

Result:

A(5) is now B

B(9) is now A

Not really simpler then just using a third variable but i works!

like image 2
Jens Krüger Avatar answered Oct 17 '22 18:10

Jens Krüger