我可以使用 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;
}
我的动机:
- 我的真实数据比较大,例如5k*5k的矩阵,所以在迭代中对已有变量赋值两次,函数内和函数外,肯定是浪费时间。
- SO 上最接近的问题是 this one,但就像问题中的 OP 一样,我的 R 会话也有很多对象:我正在使用
Rmpi
,每个从属将有大量的变量。
- 依我拙见,
R
是写在 C
中的,所以 R
可能有像 C
那样的指针,而我在净令人惊讶。
这个怎么样;这只是分配给父环境。
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.
这是实现我的目标的一种愚蠢的(也许只在我脑海中)的方法:
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;
}
我的动机:
- 我的真实数据比较大,例如5k*5k的矩阵,所以在迭代中对已有变量赋值两次,函数内和函数外,肯定是浪费时间。
- SO 上最接近的问题是 this one,但就像问题中的 OP 一样,我的 R 会话也有很多对象:我正在使用
Rmpi
,每个从属将有大量的变量。 - 依我拙见,
R
是写在C
中的,所以R
可能有像C
那样的指针,而我在净令人惊讶。
这个怎么样;这只是分配给父环境。
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.