views:

453

answers:

2

Can you pass by reference with "R" ? for example, in the following code:

setClass("MyClass",
    representation(
    name="character"
    ))


instance1 <-new("MyClass",name="Hello1")
instance2 <-new("MyClass",name="Hello2")

array = c(instance1,instance2)

instance1
array

instance1@name="World!"

instance1
array

the output is

> instance1
An object of class “MyClass”
Slot "name":
[1] "World!"

> array
[[1]]
An object of class “MyClass”
Slot "name":
[1] "Hello1"


[[2]]
An object of class “MyClass”
Slot "name":
[1] "Hello2"

but I wish it was

> instance1
An object of class “MyClass”
Slot "name":
[1] "World!"

> array
[[1]]
An object of class “MyClass”
Slot "name":
[1] "World!"


[[2]]
An object of class “MyClass”
Slot "name":
[1] "Hello2"

is it possible ?

Thanks

Pierre

+2  A: 

No, W/r/t R, in assignment statements, most objects are immutable. R will copy the object not just the reference.

As far as i know this is true not just for R's primitives (vectors, matrices, et al.) but for functions as well.

There is an R Package called R.oo that does allow you to mimic pass-by-refernece behavior; R.oo is available on CRAN.

doug
See also the `mutatr` and `proto` packages.
hadley
+2  A: 

pass-by-reference is possible for environments. You can try to use them: basically whenever you create an object you would need to create an environment slot as well. But I think that it is cumbersome. Have a look at link1 and link2.

teucer