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 reduce code repetition the following may help:
swap <- function(x,y) { eval( parse( text = paste("swap_unique_var_a<-", substitute(x), ";", substitute(x), "<-", substitute(y), ";", substitute(y), "<-swap_unique_var_a") ), env=parent.frame() )}
You can then use it as follows:
a<-1; b<-2;swap(a,b)print(a); print(b)
The two arguments of the function swap()
refer to two variables in the local frame, which it then swaps creating a temporary in order to do so.
Current limitations / issues with the swap()
function:
- Temporary is created in the
parent.frame()
which is where you are calling theswap()
from. - Arguments
x
andy
are assumed to be in theparent.frame()
environment, so variables in the global environment are re-created in theparent.frame()
environment.
It may be possible to make the function more robust, but I am a little concerned about the impact on performance, especially in an interpreted language such as R without the equivalent of in-lining.
If there is interest / time I will test performance and see if a more robust version is possible.