How do I modify an argument being passed to a function in R? In C++ this would be pass by reference.
g=4
abc <- function(x) {x<-5}
abc(g)
I think that @Dason's method is the only way to do it theoretically, but practically I think R's way already does it.
For example, when you do the following:
y <- c(1,2)
x <- y
x
is really just a pointer to a the value c(1,2)
. Similarly, when you do
abc <- function(x) {x <- 5; x}
g <- abc(g)
It is not that you are spending time copying g
to the function and then copying the result back into g
. I think what R does with the code
g <- abc(g)
is:
abc
is set up.x
.x
points to the same value that g
points to.x
points to 5x
g
now points to the same value that x
pointed to at the time of return.Thus, it is not that there is a whole bunch of unnecessary copying of large options.
I hope that someone can confirm/correct this.