[This article was first published on R HEAD, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:

set<-function(x,value){
eval.parent(substitute(x<-value))
}
valX <- 51
set(valX ,10)
valX
>[1] 10

eval.parent(substitute(x<-x+1))
}
valX <- 51
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

addOne_2<-function(x,value){
x<-x+1
eval.parent(substitute(x<-x))
}
valX <- 51
>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.

addOne_3<-function(x,value){
xx<-x
xx<-xx+1
eval.parent(substitute(x<-xx))
}
valX <- 51
valX
>[1] 52


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

Another way to implement