1

I want to emulate call by reference in R and in my search came across this link https://www.r-bloggers.com/call-by-reference-in-r/.

Using the strategy given in the link above I tried to create a function that would modify the integer vector passed to it as well as return the modified vector. Here's its implementation

library(purrr)

fun = function(top){
  stopifnot(is_integer(top))
  top1 <- top
  top1 <- c(top1,4L)
  eval.parent(substitute(top<-top1))
  top1
}

When I create a variable and pass to this function, it works perfectly as shown

> k <- c(9L,5L)
> fun(k)
[1] 9 5 4
> k
[1] 9 5 4

But when I pass the integer vector directly, it throws an error:

> fun(c(3L,4L))
 Error in c(3L, 4L) <- c(3L, 4L, 4L) : 
  target of assignment expands to non-language object 

Is there a workaround for this situation, where if a vector is passed directly, then we only return the modified vector as the result ?

Any help would be appreciated...

Shekhar
  • 11
  • 4
  • There is no workaround for this. You've essentially created a function that takes a variable name as input and modifies that variable as a side effect of running. Because `c(3L,4L)` is not a variable name, the function cannot work as intended. – jdobres Jun 21 '20 at 13:57
  • @jdobres Is there any other way I can implement pass by reference safely in R ? – Shekhar Jun 21 '20 at 14:00
  • Does this answer your question? [Can you pass-by-reference in R?](https://stackoverflow.com/questions/2603184/can-you-pass-by-reference-in-r) – jdobres Jun 21 '20 at 14:09
  • See my expanded answer. – jdobres Jun 21 '20 at 14:20

1 Answers1

0

There is no workaround for this. You've essentially created a function that takes a variable name as input and modifies that variable as a side effect of running. Because c(3L,4L) is not a variable name, the function cannot work as intended.

To be clear, what you have right now is not really pass-by-reference. Your function resembles it superficially, but is in fact using some workarounds to simply evaluate an expression in the function's parent environment, instead of its own. This type of "operation by side effect" is generally considered bad practice (such changes are hard to track and debug, and prone to error), and R is built to avoid them.

Pass-by-reference in R is generally not possible, nor have I found it necessary in over a decade of daily R use.

jdobres
  • 11,339
  • 1
  • 17
  • 37