Call by reference in R

421 篇文章 14 订阅
(This article was first published on  R HEAD, and kindly contributed to  R-bloggers)

Sometimes it is convenient to use “call by reference evaluation” inside an R function. For example, if you want to have multiple return value for your function, then either you return a list of return value and split them afterward or you can return the value via the argument.

For some reasons(I would like to know too), R do not support call by reference. The first reason come up in my mind is safety, if the function can do call by reference, it is more difficult to trace the code and debug(you have to find out which function change the value of your variables by examining the details of your function). In fact, R do “call by reference” when the value of the argument is not changed. They will make a copy of the argument only when the value is changed.  So we can expect there’s no efficiency gain (at least not a significant one) even we can do call by reference.

Anyway, it is always good to know how to have a “pseudo call by reference” in R (you can choose (not) to use it for whatever reason). The trick to implement call by reference is to make use of the eval.parent function in R. You can add a code to replace the argument value in the parent environment so that the function looks like implementing the call by reference evaluation strategy. Here are some examples of how to do it:

1
2
3
4
5
6
7
set<- function (x,value){
    eval.parent ( substitute (x<-value))
}
valX <- 51
set (valX ,10)
valX
>[1] 10
1
2
3
4
5
6
7
addOne_1<- function (x,value){
    eval.parent ( substitute (x<-x+1))
}
valX <- 51
addOne_1 (valX)
valX
>[1] 52

Note that you could not change the value of x inside the function. If you change the value of x, a new object will be created. The substitute function will replace x with the new value and hence this method wont work. For example

1
2
3
4
5
6
7
addOne_2<- function (x,value){
    x<-x+1
    eval.parent ( substitute (x<-x))
}
valX <- 51
addOne_2 (valX)
>Error in 52 <- 52 : invalid (do_set) left-hand side to assignment

If you want to change the value of x inside the function, you have to copy x to a new object and use new object as x.  At the end of the function, you can replace the value of x with the new object at the parent environment.

1
2
3
4
5
6
7
8
9
addOne_3<- function (x,value){
    xx<-x
    xx<-xx+1
    eval.parent ( substitute (x<-xx))
}
valX <- 51
addOne_3 (valX)
valX
>[1] 52

Another way to do call by reference more formally is using the R.oo packages.

Another way to implement

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值