[R] pass by reference -- how to do it
Gabor Grothendieck
ggrothendieck at myway.com
Wed Feb 18 05:19:02 CET 2004
If you don't mind NOT passing your arrays at all then you
can do this:
f <- function() a[1] <<- a[1] + 1
a <- 1:5
f() # increments first element of a by 1
a # c(2,2,3,4,5)
The <<- causes the expression to take place in the global
environment.
If you want to actually pass your arrays by reference then the
following works although its a bit messy:
g <- function(z) eval(eval(substitute(expression(z[1] <<- z[1]+1))))
a <- 1:5
g(a) # increments first element of a by 1
a # c(2,2,3,4,5)
The <<- causes the expression to be evaluated in the global
environment. expression() turns its argument into an object
of mode expression. substitute() replaces z with the argument
passed to f in that expression and returns an object of mode
call. The inner eval turns the object of mode call into an
object of mode expression and the outer eval evaluates that expression.
---
Date: Tue, 17 Feb 2004 13:23:58 -0800 (PST)
From: Robert Dodier <robert_dodier at yahoo.com>
To: <r-help at stat.math.ethz.ch>
Subject: [R] pass by reference -- how to do it
Hello,
Pass by reference appears to be a topic which comes up
from time to time, but I wasn't able to find something in
the R-help archives which tells how to accomplish it.
I have a problem that you may have seen before -- R runs
out of memory when processing large matrices. Part of the
problem for me is that I am using some large matrices as
function arguments, and these are modified, which leads
to allocating copies of the matrices.
I would like to do the modification "in place" so that
a copy is not required. Thanks for any light you can shed
on this.
If you're tempted to tell me "you don't really want to do that" --
let me save you the trouble. You are so very right! Indeed I
don't want to have pass by reference variables. OTOH I don't
want R to come to a dead halt at an inconvenient time either.
Thanks for your help,
Robert Dodier
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
More information about the R-help
mailing list