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.
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.
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
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With