How to get a link to an object stored in a list?

I have a list l:

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

And I want to get a link to the first element of this list. In other terms, I want if I do something like:

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

then lwill also be changed.

How can I do something like this in R?

+4
source share
2 answers

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

The only way to do this is through environments (or something that builds on top of the environment, such as R6 classes).

As a simple example (note that you need to specify 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

... , , . , R , .

+3

makeActiveBinding :

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

, l1 .

, , .

+2

Source: https://habr.com/ru/post/1613818/


All Articles