我可以使用 R 中的指针在函数内交换变量吗?

Can I swap variables inside a function using pointers in R?

这是实现我的目标的一种愚蠢的(也许只在我脑海中)的方法:

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]]

但我正在考虑类似于以下 C 代码的内容:

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

}

我的动机:

这个怎么样;这只是分配给父环境。

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.