4

I've got a list l:

l <- list(c(1,2),c(3,4))

And I want to retrieve the reference on the first element of this list. In other terms, I want that if I do something like :

l1 <- getRef(l,1)
l1[1] <- 0

then l would also be modified.

How can I do somthing like that in R ?

user2682877
  • 520
  • 1
  • 8
  • 19
  • It is a reference to the first element of the list. I.e modifying the object via the reference would also modify the first element of the list. – user2682877 Oct 30 '15 at 11:23
  • 1
    Maybe relevant? http://stackoverflow.com/questions/21965665/get-object-by-its-memory-address-in-r – zx8754 Oct 30 '15 at 11:24
  • R uses copy-on-modify semantics. Initially l1 points to the object at index 1. As soon as you change that object, l1 gets a copy of the original object and modifies it. No way to get around this. – kliron Oct 30 '15 at 11:29
  • @zx8754 thanks. it is. – user2682877 Oct 30 '15 at 11:30

2 Answers2

3

R does not support this because in R, all objects (except environments) have value semantics, not reference semantics.

The only way of doing this is via environments (or something building on top of environments, e.g. R6 classes).

As a simple example (note that you need to provide names here):

lenv = function (...) list2env(list(...))
l = lenv(x = lenv(a = 1, b = 2), y = lenv(a = 3, b = 4))

Now you can do

l1 = l$x
l1$a = 2
l$x$a
# 2

… but that’s convoluted, inefficient, and most of the time not what you want to do. Embrace the fact that R has value semantics rather than working against it.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

You can use makeActiveBinding function like this:

l <- list(c(1,2),c(3,4))
makeActiveBinding("l1", function() l, .GlobalEnv)
l[1] <- 0
l1
#[[1]]
#[1] 0
#
#[[2]]
#[1] 3 4

However, this way l1 is read only.

Although, generally I would discourage such constructs.

mjaskowski
  • 1,479
  • 1
  • 12
  • 16