0

Here is a silly (maybe only in my mind) way to accomplish my goal:

A <- "This is a test."
B <- "This is the answer."
swap <- function(item1,item2) {
  tmp   <- item2
  item2 <- item1
  item1 <- tmp
  return(list(item1,item2))
}
AB <- swap(A,B)
A <- AB[[1]]
B <- AB[[2]]

But I'm considering something similar to the C code following:

void swap(int *a, int *b)
{
    int iTemp ;
    iTemp = *a;
    *a = *b;
    *b = iTemp;

}

My motivations:

  • My real data is quite large, e.g. 5k*5k matrix, so the assignment of the existing variable in the iteration twice, inside the function and outside the function, must be time squandering.
  • The closest question on the SO is this one, but just like the OP in the question, my R session also has lots of objects: I'm working with Rmpi, and each slave will have a great number of variables.
  • In my humble opinion, R is written in C, so R may have pointers like C does, while I can't find much on the net surprisingly.
smci
  • 32,567
  • 20
  • 113
  • 146
Hunter Jiang
  • 1,300
  • 3
  • 14
  • 23

1 Answers1

1

How about this; this just assigns to the parent environment.

A <- "This is a test."
B <- "This is the answer."

swap <- function(item1, item2) {
  tmp <- item1
  assign(deparse(substitute(item1)), item2, pos = 1)
  assign(deparse(substitute(item2)), tmp, pos = 1)
}

swap(A, B)
A
#[1] "This is the answer."
B
#[1] "This is a test.
kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42
  • wow, thanks! This is a nice method which must optimize my existing code. – Hunter Jiang May 01 '18 at 06:58
  • @HunterJiang But please read [Why is using assign bad](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad)! I think the use of `assign` should be actively discouraged/avoided, especially if you're new to R. – Maurits Evers May 01 '18 at 07:03
  • @MauritsEvers What an interesting and helpful link! Thanks for your warmly advise. – Hunter Jiang May 01 '18 at 07:37
  • 1
    @HunterJiang You're very welcome. The [link](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad) includes posts by some of the most knowledgeable people from the R community, so definitely worth a read;-) – Maurits Evers May 01 '18 at 10:52