Skip to content

R and pointer

5 messages · Laetitia Marisa, Jeff Gentry, Brian Ripley +2 more

#
Hi everyone,

I want to write a function that modify directly variables passed as 
parameters (the equivalent in C language of  *ptr/&ptr) so that I don't 
have to return a list and to reaffect all my variables.
Is it possible to do so in R?

Thanks a lot.

Laetitia Marisa.
#
You can use environments as they're passed by reference.
#
On Fri, 29 Aug 2003, Laetitia Marisa wrote:

            
Yes, with the .Call/.External interface (and there are examples in the ts 
package).  To a limited extent it is possible with .C(DUP=FALSE), but you 
really don't want to go there.

I would want a very good understanding of R's copying semantics before 
doing this (and those are liable to change, too).
#
Three references that are of interest (the two first are related to the
idea of using environments to do the job):

 [1] http://www.maths.lth.se/help/R/ImplementingReferences/
 [2] http://www.maths.lth.se/help/R/R.oo/
 [3] http://www.omegahat.org/OOP/

All of the above are written in the light object-oriented programming,
but from [1] you quite easily get what is needed for just emulating
"pointers". Be careful though as R is a functional language.

Best wishes

Henrik Bengtsson
Lund University
#
Henrik Bengtsson wrote:

            
Cutting to what I think was the gist of the original poster's question, 
can I write a function, foo, that does this:

 > x <- 3
 > foo(x)
 > x
[1] 9

for any x, in any situation? I'm guessing its doable, but ugly...


Baz