3

Question Does R contains the concept of reference to an object.

In python, an equal operator is, in fact, a copy by reference. For example:

>> a = [1,2,3]
>> b = a
>> b[1] = 10
>> a
   [1, 10, 3]

or in C++

 vector a(3);
 a[1] = 1;
 vector& b = a;
 b[1] = 10;
 // now a[1] = 10
mnel
  • 113,303
  • 27
  • 265
  • 254
Theo
  • 1,385
  • 2
  • 10
  • 19

2 Answers2

6

You should probably look at reference classes, but you can also just use plain old environments:

> a=new.env()
> a$data=c(1,2,3)
> b=a
> b$data
[1] 1 2 3
> a$data[1]=99
> b$data
[1] 99  2  3

a and b are the same environment:

> a
<environment: 0xa1799fc>
> b
<environment: 0xa1799fc>

so their contents are the same objects.

I think some of the other R OO systems (R.oo, proto?) use environments like this to implement OO objects and methods.

So, although you can just do this, action-at-a-distance effects like this can cause very hard to find bugs, and you probably shouldn't.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
1

Yes, this feature is present in R, though I've never used it myself. Reference classes (or R5 classes as they are sometimes dubbed) have this kind of behaviour. Fairly detailed documentation are in the link below, along with an example

http://www.inside-r.org/r-doc/methods/ReferenceClasses

There are other questions on SE which link to various presentations which probably contain more examples

What is the significance of the new Reference Classes?

Community
  • 1
  • 1
Róisín Grannell
  • 2,048
  • 1
  • 19
  • 31
  • 1
    Please stop calling them R5. R Core, the people who wrote S3, S4, or Reference Classes, do not use that term which had already been deployed for another project within R. It was joke of ours which we pulled; unfortunately Hadley perpetuated it. Let's stop this. – Dirk Eddelbuettel Feb 10 '13 at 15:54