Quantcast
Viewing latest article 4
Browse Latest Browse All 9

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 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 the swap() from.
  • Arguments x and y are assumed to be in the parent.frame() environment, so variables in the global environment are re-created in the parent.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.


Viewing latest article 4
Browse Latest Browse All 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>