[R] passing the reference in R functions

Thomas Lumley tlumley at u.washington.edu
Fri Mar 8 18:19:43 CET 2002


On Fri, 8 Mar 2002, Rangrej, Jagadish wrote:

> Hello!
>
> is it possible to send the vector in the r functions without making the
> function frame to actually have the replicate copy of it ?
>

If you're asking what I think you're asking, then yes.

R appears to pass arguments by value, so when you do

  mean(verybigarray)

the effect is as if the mean() function received a copy of verybigarray.
However, R doesn't *actually* copy arguments until they are modified, so
the copy is really just a reference to the original array and takes up
very little memory.

You can see the difference by creating a large vector, say,

x<-rnorm(1e6)
gcinfo(TRUE)   #report when memory is garbage collected

system.time(mean(x))     #mean() does copy and modify its argument

system.time(sum(x)/1e6)  #sum() doesn't


You will see that mean() is slower and causes garbage collection.


	-thomas


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list